forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid-anagram.cpp
More file actions
42 lines (34 loc) · 772 Bytes
/
valid-anagram.cpp
File metadata and controls
42 lines (34 loc) · 772 Bytes
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
// Time: O(n)
// Space: O(1)
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) {
return false;
}
unordered_map<char, int> count;
for (const auto& c: s) {
++count[tolower(c)];
}
for (const auto& c: t) {
--count[tolower(c)];
if (count[tolower(c)] < 0) {
return false;
}
}
return true;
}
};
// Time: O(nlogn)
// Space: O(n)
class Solution2 {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) {
return false;
}
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};