您的位置:首页 > 其它

[LeetCode] Valid Anagram

2015-08-01 14:14 435 查看
Hash Table

This idea uses a hash table to record the times of appearances of each letter in the two strings
s
and
t
. For each letter in
s
, it increases the counter by
1
while for each letter in
t
, it decreases the counter by
1
. Finally, all the counters will be
0
if they two are anagrams of each other.

The first implementation uses the built-in
unordered_map
and takes 36 ms.

class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
int n = s.length();
unordered_map<char, int> counts;
for (int i = 0; i < n; i++) {
counts[s[i]]++;
counts[t[i]]--;
}
for (auto count : counts)
if (count.second) return false;
return true;
}
};


Since the problem statement says that "the string contains only lowercase alphabets", we can simply use an array to simulate the
unordered_map
and speed up the code. The following implementation takes 12 ms.

class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
int n = s.length();
int counts[26] = {0};
for (int i = 0; i < n; i++) {
counts[s[i] - 'a']++;
counts[t[i] - 'a']--;
}
for (int i = 0; i < 26; i++)
if (counts[i]) return false;
return true;
}
};


Sorting

For two anagrams, once they are sorted in a fixed order, they will become the same. This code is much shorter (this idea can be done in just 1 line using Python as here). However, it takes much longer time --- 76 ms in C++.

class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: