03
08/2015
[LeetCode] Valid Anagram
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.
解题思路:
这道题的难点在于弄清题意。字谜游戏,给定两个词,判断这两个词是否只有组成的字母顺序不一样。而后说明两个字符串只包含小写字母。于是我们可以用一个26长度的数组来计数。
class Solution {
public:
bool isAnagram(string s, string t) {
int len1 = s.length();
int len2 = t.length();
if(len1!=len2){
return false;
}
vector<int> count(26, 0);
for(int i=0; i<len1; i++){
count[s[i]-'a']++;
}
for(int i=0; i<len2; i++){
if(--count[t[i]-'a']<0){
return false;
}
}
return true;
}
};转载请注明:康瑞部落 » [LeetCode] Valid Anagram

0 条评论