1657. 确定两个字符串是否接近

很繁琐吼
如果排序后相等即true
然后使用两个26位的二进制数表示两个字符串,如果字母类型相同则两个二进制数异或的结果等于0,由于字母都是小写字母,于是这部分参考318. 最大单词长度乘积
然后,同时使用两个数组统计每个类型字母出现的次数,然后对两个数组排序,比较,如果相同则true,否则false

class Solution {
public:
    bool closeStrings(string word1, string word2) {
        sort(word1.begin(), word1.end());
        sort(word2.begin(), word2.end());
        if (word1 == word2) return true;
        int n1 = word1.size(), n2 = word2.size();
        int num1 = 0, num2 = 0;
        vector<int> v1(26), v2(26);
        int t = 0;
        for (int i = 0; i < n1 - 1; ++i) {
            num1 |= 1 << (word1[i] - 'a');
            if (word1[i] == word1[i + 1]) {
                v1[t]++;
            } else {
                v1[t]++;
                t++;
            }
        }
        num1 |= 1 << (word1[n1 - 1] - 'a');
        v1[t]++;

        t = 0;
        for (int i = 0; i < n2 - 1; ++i) {
            num2 |= 1 << (word2[i] - 'a');
            if (word2[i] == word2[i + 1]) {
                v2[t]++;
            } else {
                v2[t]++;
                t++;
            }
        }
        num2 |= 1 << (word2[n2 - 1] - 'a');
        v2[t]++;

        if (num1 ^ num2) return false;
        sort(v1.begin(), v1.end());
        sort(v2.begin(), v2.end());
        if (v1.size() != v2.size()) return false;

        for (int i = 0; i < v1.size(); ++i) {
            if (v1[i] != v2[i]) return false;
        } 

        return true;
    }
};

看了题解,发现v1v2可以直接设定大小等于26,并且比较可以直接v1 == v2

class Solution {
public:
    bool closeStrings(string word1, string word2) {
        sort(word1.begin(), word1.end());
        sort(word2.begin(), word2.end());
        if (word1 == word2) return true;
        int n1 = word1.size(), n2 = word2.size();
        int num1 = 0, num2 = 0;
        vector<int> v1(26), v2(26);
        for (int i = 0; i < n1; ++i) {
            num1 |= 1 << (word1[i] - 'a');
            ++v1[(word1[i] - 'a')];
        }

        for (int i = 0; i < n2; ++i) {
            num2 |= 1 << (word2[i] - 'a');
            ++v2[(word2[i] - 'a')];
        }

        if (num1 ^ num2) return false;
        sort(v1.begin(), v1.end());
        sort(v2.begin(), v2.end());
        return v1 == v2;
    }
};

你可能感兴趣的:(LeetCode,算法,数据结构)