题目链接
思路
- 这道题和上题有点类似,代码主题框架相同,并不需要像拓扑排序那样,先建图
- 注意看主题框架类似邻接矩阵!
- 还有就是注意如何判断两个字符串是不是相似的,因为题目中说了所有的字符串都是变位词,所以我们可以遍历一遍两个字符串,遇到不一样的字符就+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 ;
}
}