839. Similar String Groups
If the exchange string X
of letters in two different positions, such as the string Y
are equal, so called X
, and Y
two similar strings. If the two strings themselves are equal, then they are also similar.
For example, "tars"
and "rats"
similar (exchange 0
and 2
position); "rats"
and "arts"
also similar, but "star"
does not "tars"
, "rats"
or "arts"
similar.
In short, they form two association groups through similarity: {"tars", "rats", "arts"}
and {"star"}
. Note that "tars"
and "arts"
are in the same group, even if they are not similar. Formally, for each group, to determine a word in the group, it only needs to be similar to at least one word in the group.
Give you a list of strings strs
. Each string is a list of strs
other letter of the word ectopic all strings. Ask strs
how much of a string of similar groups?
Example 1:
输入:strs = ["tars","rats","arts","star"]
输出:2
Example 2:
输入:strs = ["omv","ovm"]
输出:1
prompt:
- 1 <= strs.length <= 100
- 1 <= strs[i].length <= 1000
- sum(strs[i].length) <= 2 * 104
- strs[i] contains only lowercase letters.
- All the words in strs have the same length and are diaphanous words of each other.
Remarks:
- Anagram is a new word formed by changing the position (order) of the letters of a string.
Method 1: Collect and check
Problem-solving ideas
The last day of January, of course, it must end with "Combined Check Collection"~~
There is no special solution, the two-layer loop honestly compares whether two strings are "similar strings". If the string is similar union
to the can together.
Reference Code
public int numSimilarGroups(String[] strs) {
int n = strs.length;
UnionFind unionFind = new UnionFind(n);
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (unionFind.connected(i, j)) {
continue;
}
if (isSimilar(strs[i], strs[j])) {
unionFind.union(i, j);
}
}
}
return unionFind.getCount();
}
// 判断两个字符串是否为“相似字符串”
public boolean isSimilar(String s1, String s2) {
char[] cs1 = s1.toCharArray(), cs2 = s2.toCharArray();
int num = 0;
for (int i = 0; i < cs1.length; i++) {
if (cs1[i] != cs2[i]) {
num++;
if (num > 2) {
return false;
}
}
}
return true;
}
// 并查集模板
class UnionFind {
private int[] parent;
private int count;
public UnionFind(int n) {
count = n;
parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
public void union(int x, int y) {
int rootX = find(x), rootY = find(y);
if (rootX == rootY) {
return;
}
parent[rootX] = rootY;
count--;
}
public int find(int x) {
return parent[x] == x ? parent[x] : (parent[x] = find(parent[x]));
}
public boolean connected(int x, int y) {
return find(x) == find(y);
}
public int getCount() {
return count;
}
}
Results of the