website/content/ChapterFour/0800~0899/0839.Similar-String-Groups.md
Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y.
For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts".
Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}. Notice that "tars" and "arts" are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.
We are given a list A of strings. Every string in A is an anagram of every other string in A. How many groups are there?
Example 1:
Input: ["tars","rats","arts","star"]
Output: 2
Note:
A.length <= 2000A[i].length <= 1000A.length * A[i].length <= 20000A consist of lowercase letters only.A have the same length and are anagrams of each other.如果我们交换字符串 X 中的两个不同位置的字母,使得它和字符串 Y 相等,那么称 X 和 Y 两个字符串相似。
例如,"tars" 和 "rats" 是相似的 (交换 0 与 2 的位置); "rats" 和 "arts" 也是相似的,但是 "star" 不与 "tars","rats",或 "arts" 相似。
总之,它们通过相似性形成了两个关联组:{"tars", "rats", "arts"} 和 {"star"}。注意,"tars" 和 "arts" 是在同一组中,即使它们并不相似。形式上,对每个组而言,要确定一个单词在组中,只需要这个词和该组中至少一个单词相似。我们给出了一个不包含重复的字符串列表 A。列表中的每个字符串都是 A 中其它所有字符串的一个字母异位词。请问 A 中有多少个相似字符串组?
提示:
备注:
anagram 的(anagram 的意思是,字符串的任意排列组合)。那么这题就比较简单了,只需要判断每两个字符串是否“相似”,如果相似就 union(),最后看并查集中有几个集合即可。
package leetcode
import (
"github.com/halfrost/leetcode-go/template"
)
func numSimilarGroups(A []string) int {
uf := template.UnionFind{}
uf.Init(len(A))
for i := 0; i < len(A); i++ {
for j := i + 1; j < len(A); j++ {
if isSimilar(A[i], A[j]) {
uf.Union(i, j)
}
}
}
return uf.TotalCount()
}
func isSimilar(a, b string) bool {
var n int
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
n++
if n > 2 {
return false
}
}
}
return true
}