839 Similar String Groups
Last updated
Was this helpful?
Last updated
Was this helpful?
Two stringsX
andY
are similar if we can swap two letters (in different positions) ofX
, so that it equalsY
.
For example,"tars"
and"rats"
are similar (swapping at positions0
and2
), 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 listA
of strings. Every string inA
is an anagram of every other string inA
. How many groups are there?
Example 1:
Note:
A.length <= 2000
A[i].length <= 1000
A.length * A[i].length <= 20000
All words inA
consist of lowercase letters only.
All words inA
have the same length and are anagrams of each other.
The judging time limit has been increased for this question.
(1) Union Find
思路: Union Find的思想比较直接,两个string只要是similar的就直接union.需要注意的是isSimilar()里,按题目要求应该是diff等于2属于similar,但为了避免输入数组中的相同string,我们把相同string也union在一起。
Union Find: 时间复杂度O(n^2 * L), 空间复杂度O(n^2)