-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathisAnagram.cpp
More file actions
75 lines (68 loc) · 1.81 KB
/
isAnagram.cpp
File metadata and controls
75 lines (68 loc) · 1.81 KB
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
/*Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
Subscribe to see which companies asked this question*/
//my Solution
#include<map>
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.length()!=t.length())
return false;
map<char,int> sci;
for(auto c:s)
if(sci.find(c)==sci.end())
sci[c]=1;
else
sci[c]++;
for(auto c:t)
{
if(sci.find(c)!=sci.end())
{
if(sci[c]>1)
sci[c]--;
else
sci.erase(c);
}else
return false;
}
return true;
}
};
//better Solution
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
int n = s.length();
unordered_map<char, int> counts;
for (int i = 0; i < n; i++) {
counts[s[i]]++;
counts[t[i]]--;
}
for (auto count : counts)
if (count.second) return false;
return true;
}
};
//better Solution
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
int n = s.length();
int counts[26] = {0};
for (int i = 0; i < n; i++) {
counts[s[i] - 'a']++;
counts[t[i] - 'a']--;
}
for (int i = 0; i < 26; i++)
if (counts[i]) return false;
return true;
}
};