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.
Hide Tags
Hide Similar Problems
用个辅助数组统计,O(n),12ms。(当然也可以用hash表)
试了一下用sort,80ms,不划算。
class Solution {
public:
bool isAnagram(string s, string t) {
int ls=s.length(), lt=t.length();
if(ls!=lt)
return false;
if(s==t)
return true;
int check[26]={0};
for(int ii=ls-1; ii>=0; ii--)
check[s[ii]-'a']++;
for(int ii=lt-1; ii>=0; ii--)
check[t[ii]-'a']--;
for(int ii=25; ii>=0; ii--)
if(0 != check[ii])
return false;
return true;
}
bool isAnagram_80ms(string s, string t) {
int ls=s.length(), lt=t.length();
if(ls!=lt)
return false;
if(s==t)
return true;
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s==t;
}
};
12 ms.
No comments:
Post a Comment