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.
很弱的题。空间和时间的balance.
省空间,用sort.
省时间,用hashtable.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isAnagram(string s, string t) { | |
if (s.size() != t.size()) return false; | |
unordered_map<char, int> a, b; | |
for (int i = 0; i<s.size(); i++) { | |
if (a.count(s[i])) { | |
a[s[i]]++; | |
} else { | |
a[s[i]] = 1; | |
} | |
} | |
for (int i = 0; i<t.size(); i++) { | |
if (b.count(t[i])) { | |
b[t[i]]++; | |
} else { | |
b[t[i]] = 1; | |
} | |
} | |
return a == b; | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isAnagram(string s, string t) { | |
sort(s.begin(), s.end()); | |
sort(t.begin(), t.end()); | |
return s==t; | |
} | |
}; |
No comments:
Post a Comment