考点
- array可以作为实现哈希表的一种数据结构
- 字母的ASCII码
解题思路
26个字母意味着array的大小为26,a-z的ASCII是连续的,所以array[0]对应a,array[1]对应b…
先遍历s,如果s中有a,则array[0]加1…
再遍历t,如果t中有a,则array[0]减1…
最后如果array中的所有元素都为0,则可认为s与t是异位词
代码
class Solution {
public:
bool isAnagram(string s, string t)
{
int record[26] = {0};
for(int i=0; i< s.size(); i++)
record[s[i] - 'a']++;
for(int i=0; i< t.size(); i++)
record[t[i] - 'a']--;
for(int i=0; i<26; i++)
{
if(record[i] != 0)
return false;
}
return true;
}
};
wirtten by myself
/*
* @lc app=leetcode.cn id=242 lang=cpp
*
* [242] 有效的字母异位词
*/
// @lc code=start
#include <string>
#include <unordered_map>
#include <iostream>
using namespace std;
class Solution {
public:
bool isAnagram(string s, string t)
{
unordered_map <char,int> mapS, mapT;
mapS = insertWord(s,mapS);
mapT = insertWord(t,mapT);
for(auto key: (mapS.size() >= mapT.size()) ? mapS : mapT)
{
if (mapS[key.first] != mapT[key.first])
return false;
}
return true;
}
unordered_map <char,int> insertWord(string word, unordered_map<char, int> mapWord)
{
for (int i=0; i<word.size(); i++)
{
mapWord[word[i]]++;
}
return mapWord;
}
void traverseUnorderedMap(unordered_map<char, int> mapWord)
{
for (auto kv: mapWord)
{
cout << kv.first << " -> " << kv.second << endl;
}
}
};
// @lc code=end
int main()
{
string s = "anagram";
string t = "nagaram";
bool ans;
Solution so;
ans = so.isAnagram(s,t);
cout << ans << endl;
return 0;
}