-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0242. Valid Anagram.cpp
48 lines (40 loc) · 1.03 KB
/
0242. Valid Anagram.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
//1. this will take O(nlogn) time
class Solution {
public:
bool isAnagram(string s, string t) {
int n1 = s.length();
int n2 = t.length();
if(n1 != n2)
return false;
sort(s.begin(), s.end());
sort(t.begin(), t.end());
for(int i = 0; i<n1; i++) {
if(s[i] != t[i])
return false;
}
return true;
}
};
// 2. we can resuce unnecesary lines from the above code
class Solution {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
};
we can further imrove this solution
using extra space
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;
}
};