[LeetCode] 839. Similar String Groups

김민우·2023년 4월 28일
0

알고리즘

목록 보기
181/189

- Problem

839. Similar String Groups

- 내 코드 (Union-find)

class Solution:
    def numSimilarGroups(self, strs: List[str]) -> int:
        def find(x):
            if x != parents[x]:
                parents[x] = find(parents[x])
            return parents[x]
            
        def union(x, y):
            parents[find(x)] = find(y)

        def is_similar_string(s1, s2):
            return sum(c1 != c2 for c1, c2 in zip(s1, s2)) in [0, 2]

        parents = {s: s for s in strs}

        for i in range(len(strs)):
            for j in range(i+1, len(strs)):
                if is_similar_string(strs[i], strs[j]):
                    union(strs[i], strs[j])

        return len({find(s) for s in strs})

- 결과

profile
Pay it forward.

0개의 댓글