#1657. Determine if Two Strings Are Close

ยท

1 min read

https://leetcode.com/problems/determine-if-two-strings-are-close/description/?envType=daily-question&envId=2024-01-14


var closeStrings = function(word1, word2) {
    const freq1 = new Array(26).fill(0)
    const freq2 = new Array(26).fill(0)

    const set1 = new Set()
    const set2  = new Set()

    for (let char of word1) {
        freq1[char.charCodeAt(0) - 'a'.charCodeAt(0)]++
        set1.add(char)
    }

    for (let char of word2) {
        freq2[char.charCodeAt(0) -  'a'.charCodeAt(0)]++
        set2.add(char)
    }

    freq1.sort((a,b) => a -b)
    freq2.sort((a,b) => a - b)

     for (let element of set1) {
        if (!set2.has(element)) {
            return false;
        }
    }

    return JSON.stringify(freq1) === JSON.stringify(freq2)
};
ย