242. Valid Anagram
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = “anagram”, t = “nagaram”
Output: true
Example 2:
Input: s = “rat”, t = “car”
Output: 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?
Solution1:
使用sortclass 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());
for (int i = 0; i < s.length(); i++) {
if (s[i] != t[i]) return false;
}
return true;
}
};
简化版本class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
if (s == t) return true;
return false;
}
};
Solution2:
建立Hash表, key是char, 对应该字符出现的次数. 一个字符串加一个字符串减。
这里使用散列表实现的unodered_map
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
unordered_map<char, int> counts;
for (int i = 0; i < s.length(); i++) {
counts[s[i]]++;
counts[t[i]]--;
}
for (auto count : counts) {
if (count.second) return false;
}
return true;
}
};
Solution3
用ascii码作为key值, 不用map容器用数组class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
int counts[26];
memset(counts, 0, sizeof(counts));
for (int i = 0; i < s.length(); i++) {
counts[s[i] - 'a']++;
counts[t[i] - 'a']--;
}
for (int i = 0; i < 26; i++) {
if (counts[i]) return false;
}
return true;
}
};