Leetcode 242. Valid Anagram

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Valid Anagram

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};
  • Version 2
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
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size() != t.size()) {
return false;
}
map<char, int> m;
for(int i = 0; i < s.size(); i++) {
m[s[i]]++;

}
for(int i = 0; i < t.size(); i++) {
m[t[i]]--;
if(m[t[i]] < 0) {
return false;
}
}
for(auto iter : m) {
if(iter.second != 0) {
return false;
}
}
return true;
}
};
  • Version 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size() != t.size()) {
return false;
}
vector<int> alpha(26);
for(char ch : s) {
alpha[ch - 'a']++;
}
for(char ch : t) {
alpha[ch - 'a']--;
}
for(int x : alpha) {
if(x != 0) {
return false;
}
}
return true;
}
};

Reference

  1. https://leetcode.com/problems/valid-anagram/description/
如果有收获,可以请我喝杯咖啡!