1. 程式人生 >實用技巧 >其它 >LeetCode 每日一題839. 相似字串組

LeetCode 每日一題839. 相似字串組


技術標籤:每日一題javaleetcode字串演算法

839. 相似字串組

如果交換字串 X 中的兩個不同位置的字母,使得它和字串 Y 相等,那麼稱 X 和 Y 兩個字串相似。如果這兩個字串本身是相等的,那它們也是相似的。

例如,"tars" 和 "rats" 是相似的 (交換 0 與 2 的位置); "rats" 和 "arts" 也是相似的,但是 "star" 不與 "tars","rats",或 "arts" 相似。

總之,它們通過相似性形成了兩個關聯組:{"tars", "rats", "arts"} 和 {"star"}。注意,"tars" 和 "arts" 是在同一組中,即使它們並不相似。形式上,對每個組而言,要確定一個單詞在組中,只需要這個詞和該組中至少一個單詞相似。

給你一個字串列表 strs。列表中的每個字串都是 strs 中其它所有字串的一個字母異位詞。請問 strs 中有多少個相似字串組?

示例 1:

輸入:strs = ["tars","rats","arts","star"]
輸出:2

示例 2:

輸入:strs = ["omv","ovm"]
輸出:1

提示:

  • 1 <= strs.length <= 100
  • 1 <= strs[i].length <= 1000
  • sum(strs[i].length) <= 2 * 104
  • strs[i] 只包含小寫字母。
  • strs 中的所有單詞都具有相同的長度,且是彼此的字母異位詞。

備註:

  • 字母異位詞(anagram),一種把某個字串的字母的位置(順序)加以改換所形成的新詞。

方法一:並查集

解題思路

一月的最後一天,當然要以「並查集」結束啦~~

並沒有特別的解法,兩層迴圈老老實實地比較兩個字串是否為“相似字串”。若為相似字串 union 到一起即可。

參考程式碼

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;
    }
}

執行結果

LeetCode 每日一題839. 相似字串組