[LeetCode 242] 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?
DiffcultyEasy
Similar Problems
[LeetCode 74] Group Anagrams Medium
[LeetCode 74] Palindrome Permutation Easy
[LeetCode 74] Find All Anagrams in a String Easy
Analysis
// 这不算一道难题,核心点就在于使用哈希表映射,我们还是用一个数组来代替哈希表, // 使用类似方法的题目有Minimum Window Substring 最小窗口子串,Isomorphic Strings 同构字符串, // Longest Substring Without Repeating Characters 最长无重复子串 // 和 1.1 Unique Characters of a String 字符串中不同的字符。 // 我们先判断两个字符串长度是否相同,不相同直接返回false。 // 然后把s中所有的字符出现个数统计起来,存入一个大小为26的数组中,因为题目中限定了输入字符串为小写字母组成。 // 然后我们再来统计t字符串,如果发现不匹配则返回false。 参见代码如下:
class Solution { public: bool isAnagram(string s, string t) { int m = (int)s.size(); int n = (int)t.size(); if(m != n) return false;
int hash[26] = {0};
for(int i = 0; i < m; ++i){
hash[s[i] - 'a']++;
}
for(int i = 0; i < n; ++i){
if(--hash[t[i] - 'a'] < 0)
return false;
}
return true;
}
};
class Solution { public: bool isAnagram(string s, string t) { sort(s.begin(), s.end()); sort(t.begin(), t.end()); return s==t; } };