0%

242. 有效的字母异位词

242. 有效的字母异位词

hash

如果元素只有a-z,用数组代替hash是基本操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size() != t.size())
return false;
int memo[26]{};
for(auto ch : s)
++memo[ch - 'a'];
for(auto ch : t)
if(--memo[ch - 'a'] < 0)
return false;
return true;
}
};

如果要支持unicode需要改用hash

c++中char只有4位,而utf-8有8位,所以可能需要wchar_t

排序
1
2
3
4
5
6
7
8
9
10
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size() != t.size())
return false;
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};