LeetCode839. Similar String Groups——并查集

一、题目

Two strings, X and Y, are considered similar if either they are identical or we can make them equivalent by swapping at most two letters (in distinct positions) within the string X.

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 strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there?

Example 1:

Input: strs = [“tars”,“rats”,“arts”,“star”]
Output: 2
Example 2:

Input: strs = [“omv”,“ovm”]
Output: 1

Constraints:

1 <= strs.length <= 300
1 <= strs[i].length <= 300
strs[i] consists of lowercase letters only.
All words in strs have the same length and are anagrams of each other.

二、题解

class Solution {
public:
    int father[301];
    int nums;
    int numSimilarGroups(vector<string>& strs) {
        int n = strs.size();
        int m = strs[0].size();
        build(n);
        for(int i = 0;i < n;i++){
            for(int j = i + 1;j < n;j++){
                if(find(i) != find(j)){
                    int diff = 0;
                    for(int k = 0;k < m && diff < 3;k++){
                        if(strs[i][k] != strs[j][k]) diff++;
                    }
                    if(diff == 0 || diff == 2) unions(i,j);
                }
            }
        }
        return nums;
    }
    void build(int m){
        for(int i = 0;i < m;i++){
            father[i] = i;
        }
        nums = m;
    }
    int find(int x){
        if(x != father[x]) father[x] = find(father[x]);
        return father[x];
    }
    void unions(int x,int y){
        int fx = find(x),fy = find(y);
        if(fx != fy){
            father[fx] = fy;
            nums--;
        }
    }
};
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值