题目:
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?
解答:
class Solution {
public:
bool isAnagram(string s, string t) {
vector<int> count(26, 0);
//将词s字母频计入表中
for (int i = 0; i < s.size(); i++)
count[s[i] - 'a'] ++;
//减去也在j中出现的字母
for (int j = 0; j < t.size(); j++)
count[t[j] - 'a'] --;
//遍历数组,出现不为零的情况则返回false
for (int k = 0; k < 26; k++)
if (count[k] != 0)
return false;
return true;
}
};
还有一种做法
核心语句:
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s==t;
复杂度:O(nlogn)