题目
如果交换字符串 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
提示
1 <= strs.length <= 100
1 <= strs[i].length <= 1000
sum(strs[i].length) <= 2 * 104
strs[i] 只包含小写字母。
strs 中的所有单词都具有相同的长度,且是彼此的字母异位词。
题解
- 对于每两个相似的字符串,我们将其合并到一个连通分量中
- 相似的字符串:相等,交换两个不同位置的字母后相等
- 最后整个并查集内连通分量的个数即为相似字符串的组数
参考代码
class Solution {
public int numSimilarGroups(String[] strs) {
UnionFind myUnionFind = new UnionFind(strs.length);
for(int i = 0; i < strs.length; i++) {
for(int j = i + 1; j < strs.length; j++) {
if(isVaild(strs[i], strs[j])) myUnionFind.union(i, j);
}
}
return myUnionFind.getCount();
}
public boolean isVaild(String s1, String s2) {
if(s1.equals(s2)) return true;
int count = 0;
for(int i = 0; i < s1.length(); i++) {
if(s1.charAt(i) != s2.charAt(i)) count++;
}
return count <= 2;
}
class UnionFind {
int[] parent;
int[] rank;
int count;
public UnionFind(int n) {
parent = new int[n];
rank = new int[n];
this.count = n;
Arrays.fill(rank, 1);
for(int i = 0; i < n; i++) {
parent[i] = i;
}
}
public int getCount() {
return count;
}
public void union(int a, int b) {
int rootA = find(a);
int rootB = find(b);
if(rootA == rootB) return;
if(rank[rootA] < rank[rootB]) {
parent[rootA] = rootB;
} else {
if(rank[rootA] == rank[rootB]) {
rank[rootA]++;
}
parent[rootB] = rootA;
}
count--;
}
public boolean isConnected(int a, int b) {
int rootA = find(a);
int rootB = find(b);
return rootA == rootB;
}
public int find(int index) {
if(index != parent[index]) {
return find(parent[index]);
}
return index;
}
}
}