Valid Anagram
题目描述:
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
题目思路:
分别用哈希表记录两个字符串中字母出现的次数,对比两个字符串出现字符的次数是否都相同,如有不同,则不是anagram
题目代码:
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.length() != t.length()) return false;
int table1[256] = {0};
int table2[256] = {0};
for(int i = 0; i < s.length(); i++){
table1[s[i]]++;
table2[t[i]]++;
}
for(int i = 0; i < 256; i++){
if(table1[i] != table2[i])
return false;
}
return true;
}
};