lintcode: (158) Two Strings Are Anagrams
1.题目
Write a method anagram(s,t) to decide if two strings are anagrams or not.
Example
Given s=“abcd”, t=“dcab”, return true.
Challenge
O(n) time, O(1) extra space
2.思路及代码
1.
class Solution:
"""
@param s: The first string
@param b: The second string
@return true or false
"""
def anagram(self, s, t):
return collections.Counter(s) == collections.Counter(t)
2.
class Solution:
"""
@param s: The first string
@param b: The second string
@return true or false
"""
def anagram(self, s, t):
return sorted(s) == sorted(t)
3.
class Solution {
public:
/**
* @param s: The first string
* @param b: The second string
* @return true or false
*/
bool anagram(string s, string t) {
if (s.empty() || t.empty()) {
return false;
}
if (s.size() != t.size()) {
return false;
}
int letterCount[256] = {0};
for (int i = 0; i != s.size(); ++i) {
++letterCount[s[i]];
--letterCount[t[i]];
}
for (int i = 0; i != t.size(); ++i) {
if (letterCount[t[i]] != 0) {
return false;
}
}
return true;
}
};