[leetcode, JS] 2506. Count Pairs Of Similar Strings

mxxn·2024년 6월 1일
0

leetcode

목록 보기
168/198

문제

문제 링크 : Count Pairs Of Similar Strings

풀이

/**
 * @param {string[]} words
 * @return {number}
 */
var similarPairs = function(words) {
    let result = 0
    for(let i = 0; i<words.length; i++) {
        for(let j = i+1; j<words.length; j++) {
            const firstWord = [...new Set(words[i])].sort().join('')
            const secondWord = [...new Set(words[j])].sort().join('')
            if(firstWord === secondWord) result ++
        }
    }
    return result
};
  1. 이중 for문으로 중복제거 및 정렬한 문자들을 비교하는 방식
  • Runtime 1240 ms, Memory 56.24 MB

다른 풀이

/**
 * @param {string[]} words
 * @return {number}
 */
var similarPairs = function(words) {
    const newWords = []
    let count = 0

    // use hashSet to filter the duplicate words and sort the word.
    for (let i = 0; i < words.length; i++) {
        newWords[i] = [...new Set(words[i])].sort().join('')
    }

    // find if the word are the same for current and next.
    for (let i = 0; i < newWords.length - 1; i++) {
        for (let j = i+1; j < newWords.length; j++) {
            if (newWords[i] === newWords[j]) {
                count += 1
            }
        }
    }

    return count
};
  1. 다른 풀이를 참고
  2. word를 중복제거하고 정렬하는 for문을 새로 만들면서 배열에 넣고
  3. 해당 배열로 비교하는 방식
  4. 훨씬 더 효율적
  • Runtime 68 ms, Memory 55.93 MB
profile
내일도 글쓰기

0개의 댓글