题目
如果交换字符串 X 中的两个不同位置的字母,使得它和字符串 Y 相等,那么称 X 和 Y 两个字符串相似。如果这两个字符串本身是相等的,那它们也是相似的。
例如,"tars" 和 "rats" 是相似的 (交换 0 与 2 的位置); "rats" 和 "arts" 也是相似的,但是 "star" 不与 "tars","rats",或 "arts" 相似。
总之,它们通过相似性形成了两个关联组:{"tars", "rats", "arts"} 和 {"star"}。注意,"tars" 和 "arts" 是在同一组中,即使它们并不相似。形式上,对每个组而言,要确定一个单词在组中,只需要这个词和该组中至少一个单词相似。
给你一个字符串列表 strs。列表中的每个字符串都是 strs 中其它所有字符串的一个字母异位词。请问 strs 中有多少个相似字符串组?
示例 1:
输入: strs = ["tars","rats","arts","star"]
输出: 2
示例 2:
输入: strs = ["omv","ovm"]
输出: 1
解法
这道题做的还是顺利,又是并查集的问题,然后也可以用dfs去做,dfs做的话时间效率会更高,在这因为它主要考察的是并查集,我就用并查集的想法去做了
class Solution {
public int numSimilarGroups(String[] strs) {
int n = strs.length;
HashMap<String, Integer> map = new HashMap<>();
Union u = new Union(n);
for(int i = 0;i < n;i ++) {
for(int j = i + 1;j < n;j ++) {
if(check(strs[i], strs[j])) {
u.gather(i, j);
}
}
}
HashSet<Integer> set = new HashSet<>();
for(int i = 0;i < n;i ++) {
int p = u.find(i);
if(!set.contains(p)) {
set.add(p);
}
}
return set.size();
}
public boolean check(String s1, String s2) {
char d1 = 'A', d2 = 'A';
for(int i = 0;i < s1.length();i ++) {
if(s1.charAt(i) != s2.charAt(i)) {
if(d1 == 'A') {
d1 = s1.charAt(i);
d2 = s2.charAt(i);
} else {
if(!(d2 == s1.charAt(i)) || !(d1 == s2.charAt(i))) {
return false;
}
}
}
}
return true;
}
}
class Union {
int[] parent;
public Union(int n) {
parent = new int[n];
for(int i = 0; i < n;i ++) {
parent[i] = i;
}
}
int find(int a) {
if(parent[a] == a) {
return a;
}
return parent[a] = find(parent[a]);
}
void gather(int a, int b){
parent[find(a)] = find(b); // b作为父类
}
}
以上是我的AC代码,若有不懂请在评论区留言看到就会解答的