2022/12/22

LeetCode 1657. Determine if Two Strings Are Close

問題:判斷兩個字串是否接近
解法:將兩個字串根據a-z塞入HashMap,最後將兩個文字的HashMap key和values排序後判斷是否相同即可
JavaScript
/**
 * @param {string} s
 * @return {boolean}
 */
/**
 * @param {string} word1
 * @param {string} word2
 * @return {boolean}
 */
var closeStrings = function (word1, word2) {
    const MAX_SIZE = Math.pow(10, 5);
    if (word1.length < 1 || word1.length > MAX_SIZE || word2.length < 1 || word2.length > MAX_SIZE) {
        return;
    }

    if (word1.length != word2.length) {
        return false;
    }

    const word1Map = new Map();
    const word2Map = new Map();
    for (let i = 'a'.charCodeAt(0); i <= 'z'.charCodeAt(0); i++) {
        let c = String.fromCharCode(i);
        if (word1.indexOf(c) <= -1 && word2.indexOf(c) <= -1) {
            continue;
        }

        if (word1.indexOf(c) > -1) {
            const len = word1.length;
            word1 = word1.replaceAll(c, "");
            word1Map.set(c, len - word1.length);
        }

        if (word2.indexOf(c) > -1) {
            const len = word2.length;
            word2 = word2.replaceAll(c, "");
            word2Map.set(c, len - word2.length);
        }
    }

    if (Array.from(word1Map.keys()).sort().join("") !== Array.from(word2Map.keys()).sort().join("")
        || Array.from(word1Map.values()).sort().join("") !== Array.from(word2Map.values()).sort().join("")) {
        return false;
    }

    return true;
};