解题思路
用哈希表分别记录两个字符串对应字母出现次数即可。构建哈希表需要注意以下几点:
1.c++字符串处理:
两个单字符相减相当于计算它们的ASCLL码差值
比如说
int temp;
temp = 'c' - 'a'; //注意这里一定要用单引号,不能用双引号,否则将会编译出错
printf("%d", temp);
输出:2;
2.c++字符串可以看作字符串数组,可以直接用下标输出任意位置字母;
比如说
string s = "apple";
cout << s[3] << endl;
输出:l
3.bool变量只有0和1两种值。
如果对bool值为0的变量-1,那么会得到1;
同理,对bool值为0的变量+1, 那么会得到0,并不会报错。
完整代码
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
bool isAnagram(string s, string t)
{
int l = s.size();
if(t.size() != s.size())
return false;
int hashset[26] = {0};
for(int i = 0; i < l; i++)
hashset[s[i]-'a'] += 1;
for(int i = 0; i < t.size(); i++)
hashset[t[i]-'a'] -= 1;
for(int i = 0; i < 26; i++)
if(hashset[i] != 0)
return false;
return true;
}
};
int main()
{
Solution sol;
string s = "aacc";
string t = "ccac";
bool out = sol.isAnagram(s, t);
cout << out << endl;
return 0;
}