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.
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size() != t.size()) return false;
int arr[26];
memset(arr, 0, 26 * sizeof(int));
for(int i = 0; i < s.size(); i++){
arr[s[i]-'a'] += 1;
}
for(int i = 0; i < t.size(); i++){
arr[t[i]-'a'] -= 1;
}
for(int i = 0; i < 26; i++){
if(arr[i] != 0)return false;
}
return true;
}
};

本文介绍了一种使用C++实现的方法来判断两个字符串是否互为字谜(anagram)。通过统计每个字符串中各字母出现的次数并比较这些计数,可以高效地解决这一问题。
686

被折叠的 条评论
为什么被折叠?



