程式語言 - LeetCode - C++ - 1657. Determine if Two Strings Are Close



參考資訊:
https://www.cnblogs.com/cnoodle/p/14325580.html

題目:


解答:

class Solution {
public:
    bool closeStrings(string word1, string word2) {
        int i = 0;
        vector<int> w1cnt(26, 0);
        vector<int> w2cnt(26, 0);

        for (i = 0; i < word1.size(); i++) {
            w1cnt[word1[i] - 'a'] += 1;
        }

        for (i = 0; i < word2.size(); i++) {
            w2cnt[word2[i] - 'a'] += 1;
        }

        for (i = 0; i < 26; i++) {
            if ((w1cnt[i] > 0) && (w2cnt[i] == 0)) {
                return false;
            }

            if ((w2cnt[i] > 0) && (w1cnt[i] == 0)) {
                return false;
            }
        }

        std::sort(w1cnt.begin(), w1cnt.end());
        std::sort(w2cnt.begin(), w2cnt.end());

        for (i = 0; i < 26; i++) {
            if (w1cnt[i] != w2cnt[i]) {
                return false;
            }
        }

        return true;
    }
};