其他分享
首页 > 其他分享> > LeetCode - 839 相似字符串组

LeetCode - 839 相似字符串组

作者:互联网

在这里插入图片描述
在这里插入图片描述

class Solution {
    String[] copy;
    public int numSimilarGroups(String[] strs) {
        int n = strs.length;
        copy = strs;
        UnionFind uf = new UnionFind(n);
        for(int i =0;i < n-1;i++){
            for(int j = i+1;j<n;j++){
                if(isSimilar(strs[i],strs[j]) == true)
                  uf.union(i,j);
            }
        }
        return uf.getCount();
    }
    public boolean isSimilar(String str1,String str2)
    {
         int num = 0;
        for (int i = 0; i < str1.length(); i++) {
            if (str1.charAt(i) != str2.charAt(i)) {
                num++;
                if (num > 2) {
                    return false;
                }
            }
        }
        return true;
    }
    public class UnionFind{
        int[] parent;
        int[] rank;
        int count;
        public int getCount(){
            return count;
        }
        public UnionFind(int n){
            parent = new int[n];
            rank = new int[n];
            count = n;
            for(int i = 0;i < n;i++){
                parent[i] = i;
                rank[i] = 1;
            }
        }
        public int find(int x){
            if(parent[x] != x){
                parent[x] = find(parent[x]);
            }
            return parent[x];
        }
         public void union(int x,int y){
            int rootX = find(x);
            int rootY = find(y);
            if(rootX == rootY)
               return ;
            if(rank[rootX] == rank[rootY]){
                parent[rootX] = rootY;
                rank[rootY] += 1;
            }
            else if(rank[rootX] > rank[rootY]){
                parent[rootY] = rootX;
            }
            else{
                parent[rootX] = rootY;
            }
            count -= 1;
        }
    }
}

标签:parent,int,839,rank,public,rootY,rootX,字符串,LeetCode
来源: https://blog.csdn.net/qq_44822951/article/details/122793678