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