c_cpp 242.有效的Anagram
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 242.有效的Anagram相关的知识,希望对你有一定的参考价值。
//Runtime: 28 ms, faster than 25.25%
//Memory Usage: 9.8 MB, less than 5.16%
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.length() != t.length()) return false;
vector<char> array1,array2;
for(int i = 0;i < s.length();++i){
array1.push_back(s[i]);
array2.push_back(t[i]);
}
sort(array1.begin(),array1.end());
sort(array2.begin(),array2.end());
for(int i = 0;i < s.length();++i)
if(array1[i] != array2[i])
return false;
return true;
}
};
//Runtime: 16 ms, faster than 58.39%
//Memory Usage: 9.3 MB, less than 15.23%
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.length() != t.length()) return false;
unordered_map<char,int> set1,set2;
for(int i = 0;i < s.length();++i){
set1[s[i]]++,set2[t[i]]++;
}
for(int i = 0;i < s.length();++i)
if(set1[s[i]] != set2[s[i]])
return false;
return true;
}
};
//进一步优化
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;
}
};
//Runtime: 12 ms, faster than 97.85%
//Memory Usage: 9.2 MB, less than 58.97%
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.length() != t.length()) return false;
int counts[26] = {0};
for(int i = 0;i < s.length();++i){
counts[s[i] - 'a']++;
counts[t[i] - 'a']--;
}
for(int i = 0;i < 26;++i)
if(counts[i]) return false;
return true;
}
};
//Runtime: 28 ms, faster than 25.25%
//Memory Usage: 9.2 MB, less than 58.97%
class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};
以上是关于c_cpp 242.有效的Anagram的主要内容,如果未能解决你的问题,请参考以下文章
java 242.有效的Anagram.java
java 242.有效的Anagram.java
java 242.有效的Anagram.java
java 242.有效的Anagram.java
java 242.有效的Anagram.java
LeetCode 242. 有效的字母异位词(Valid Anagram)