题目:
今天这题我一开始就是想着用数组的方式去做。后来想了想,应该用哈希表会更好一点。然后就用哈希表自己做了一遍,确实可以。但是答案的代码比我简洁,我就直接贴上了
1.哈希表
C++代码(附带测试)
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) {
return false;
}
vector<int> table(26, 0);
for (auto& ch: s) {
table[ch - 'a']++;
}
for (auto& ch: t) {
table[ch - 'a']--;
if (table[ch - 'a'] < 0) {
return false;
}
}
return true;
}
};
int main()
{
bool iseuqals = false;
string s = "anagram";
string t = "nagaram";
Solution solution;
iseuqals = solution.isAnagram(s,t);
cout<<iseuqals<<endl;
}
今天这题可以说是比较简单的了。然后翻看题解的时候发现了一个思路上更简单的做法,虽然效率可能不太够。
这个做法就是使用Sort函数对两个字符串进行排序,然后判断等不等就可以了!这确实是个十分简洁的思路,贴上代码:
2.Sort函数
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) {
return false;
}
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};