LeetCode 839. Similar String Groups
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 unique strings. Every string in A is an anagram of every other string in A. How many groups are there?
Example 1:
1 | Input: ["tars","rats","arts","star"] |
Note:
A.length <= 2000A[i].length <= 1000A.length * A[i].length <= 20000- All words in
Aconsist of lowercase letters only. - All words in
Ahave the same length and are anagrams of each other. - The judging time limit has been increased for this question.
一个分类问题,一下就想到用并查集来做,因为放宽了时间要求所以并不是很难。判断两个字符串是否相似比较简单,看能不能通过一次swap得到就行了。一开始每个字符串自己一个集合,然后对于每一个字符串,遍历所有已经分类过的字符串,如果有相似的,就把它们所在的集合合并。
1 | class Solution { |