[LeetCode] Count Pairs Of Similar Strings

아르당·2026년 9월 16일

LeetCode

목록 보기
531/584
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

인덱스가 0부터 시작하는 문자열 배열 words가 주어진다.
2개의 문자열은 같은 문자로 구성된 경우 비슷하다.

  • 예를 들어, "abca"와 "cba"는 둘 다 문자 'a', 'b', 'c'로 구성되어서 비슷하다.
  • 그러나, "abacba"와 "bcfd"는 같은 문자로 구성되지 않아서 비슷하지않다.

0 <= i < j <= word.length - 1을 만족하고 두 문자열 words[i]와 words[j]가 서로 유사한 쌍(i, j)의 개수를 반환해라.

Example

#1
Input: words = ["aba", "aabb", "abcd", "bac", "aabc"]
Output: 2

#2
Input: words = ["aabb", "ab", "ba"]
Output: 3

#3
Input: words = ["nba", "cba", "dba"]
Output: 0

Constraints

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i]는 오직 영어 소문자로 구성된다.

Solved

class Solution {
    public int similarPairs(String[] words) {
        int count = 0;

        for(int i = 0; i < words.length - 1; i++){
            for(int j = i + 1; j < words.length; j++){
                count += charCount(words[i], words[j]);
            }
        }

        return count;
    }

    private int charCount(String s1, String s2){
        Set<Character> set1 = new HashSet<>();

        for(char c : s1.toCharArray()){
            set1.add(c);
        }

        Set<Character> set2 = new HashSet<>();

        for(char c : s2.toCharArray()){
            set2.add(c);
        }

        return set1.equals(set2) ? 1 : 0;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글