[LeetCode]242. Valid Anagram
题目描述
思路
1 hash map 对s中计数加,对t中计数减,结果不为0或者不存在的直接返回false
2 sort 直接排序后 返回 s == t ,效率最低
3 array, 初始化一个长度为26,值为0的数组,对字符串同时遍历,最后检查数组元素,有不为0的元素直接返回false
代码
#include<iostream>
#include<string>
#include<vector>
#include<unordered_map>
#include<algorithm>
using namespace std;
class Solution {
public:
bool isAnagram(string s, string t) {
/*
// unordered map
if (s.size() > t.size())
swap(s, t);
unordered_map<char, int> m;
for (char ch : s)
++m[ch];
for (char ch : t) {
if (m.count(ch) && m[ch] > 0) {
--m[ch];
}
else {
return false;
}
}
return true;
*/
/*
//sort
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
*/
//array
if (s.size() != t.size())
return false;
vector<int> counts(26, 0);
for (int i = 0; i < s.size(); ++i) {
counts[s[i] - 'a'] ++;
counts[t[i] - 'a'] --;
}
for (int i = 0; i < 26; ++i)
if (counts[i])
return false;
return true;
}
};
int main() {
Solution s;
cout << s.isAnagram("ab", "a") << endl;
system("pause");
}