面试题 01.02. 判定是否互为字符重排
程序员文章站
2022-04-03 08:53:04
...
面试题 01.02. 判定是否互为字符重排 - 力扣(LeetCode)
简单的哈希表思路,遍历计数即可:
class Solution {
public:
bool CheckPermutation(string s1, string s2) {
if(s1.size() != s2.size()) return false;
int count[26] = {0};
for(int i = 0; i < s1.size(); ++i){
++count[s1[i]-'a'];
--count[s2[i]-'a'];
}
for(int i = 0; i < 26; ++i){
if(count[i] != 0) return false;
}
return true;
}
};
或者排序:
class Solution {
public:
bool CheckPermutation(string s1, string s2) {
if(s1.size() != s2.size()) return false;
sort(s1.begin(), s1.end());
sort(s2.begin(), s2.end());
return s1 == s2;
}
};