剑指offer 专项突破版 117、相似的字符串

题目链接

思路
  • 这道题和上题有点类似,代码主题框架相同,并不需要像拓扑排序那样,先建图
  • 注意看主题框架类似邻接矩阵!
  • 还有就是注意如何判断两个字符串是不是相似的,因为题目中说了所有的字符串都是变位词,所以我们可以遍历一遍两个字符串,遇到不一样的字符就+1,最后如果不相同的字符串<=2 那么就说明是相似的
class Solution {
    public int numSimilarGroups(String[] strs) {
        int[] fathers = new int[strs.length];
        int result = strs.length;

        for(int i = 0 ; i < strs.length ;i++)
            fathers[i] = i;
        
        for(int i = 0 ; i < strs.length ; i++){
            for(int j = i + 1 ; j < strs.length ; j++){
                if(isSimilar(strs[i],strs[j]) && union(fathers,i,j))
                    result--;
            }
        }
        return result;
    }

    private int findFather(int[] fathers , int index){
        if(fathers[index] != index)
            fathers[index] = findFather(fathers,fathers[index]);
        
        return fathers[index];
    }

    private boolean union(int[] fathers , int i , int j){
        int fatherOfI = findFather(fathers,i) , fatherOfJ = findFather(fathers,j);
        if(fatherOfI == fatherOfJ)
            return false;
        
        fathers[fatherOfI] = fatherOfJ;
        return true;
    }

    private boolean isSimilar(String str1 , String str2){
        int different = 0;
        for(int i = 0 ; i < str1.length() ; i++){
            if(str1.charAt(i) != str2.charAt(i))
                different++;
        }
        return different <= 2 ;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值