欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

面试题 01.02. 判定是否互为字符重排

程序员文章站 2022-04-03 08:53:04
...

面试题 01.02. 判定是否互为字符重排 - 力扣(LeetCode)

面试题 01.02. 判定是否互为字符重排
简单的哈希表思路,遍历计数即可:

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;
    }
};
相关标签: 面试金典