-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.cpp
80 lines (77 loc) · 1.69 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
#include <algorithm>
#include <string>
#include <unordered_map>
using namespace std;
// 用数组模拟
class Solution {
public:
bool isAnagram(string s, string t) {
int hashmap[26] = {0};
if(s.size() != t.size())
return false;
for(int i = 0; i < s.size(); ++i)
{
hashmap[s[i] - 'a'] ++;
hashmap[t[i] - 'a'] --;
}
for(int i = 0; i < 26; ++i)
{
if(hashmap[i] > 0)
return false;
}
return true;
}
};
/***
用hashmap存储每个字符出现的次数,如果两个字符串的字符出现的次数一致,返回true;
***/
/*
class Solution {
public:
bool isAnagram(string s, string t) {
unordered_map<char, int> umap;
if(s.size() != t.size())
return false;
for(int i = 0; i < s.size(); ++i)
{
umap[s[i]]++;
}
for(int i = 0; i < t.size(); ++i)
{
if(umap[t[i]] > 0)
umap[t[i]]--;
}
for(unordered_map<char,int>::iterator it = umap.begin(); it != umap.end(); it++)
{
if(it -> second > 0)
return false;
}
return true;
}
};
*/
/***
思路一: 首先判断两个字符串的大小是否相等,如果不相等直接返回错误。
然后对两个字符串进行排序,比较两个字符串排序后的结果。
***/
/*
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size() != t.size())
return false;
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};
*/
int main()
{
Solution s;
string str1 = "eat";
string str2 = "eta";
cout << s.isAnagram(str1, str2) << endl;
return 0;
}