1061. 按字典序排列最小的等效字符串

给出长度相同的两个字符串s1s2 ,还有一个字符串 baseStr 。 其中 s1[i]s2[i] 是一组等价字符。 举个例子,如果 s1 = "abc"s2 = "cde",那么就有 'a' == 'c', 'b' == 'd', 'c' == 'e'。 等价字符遵循任何等价关系的一般规则: 自反性 :'a' == 'a' 对称性 :'a' == 'b' 则必定有 'b' == 'a' 传递性 :'a' == 'b''b' == 'c' 就表明 'a' == 'c' 例如, s1 = "abc"s2 = "cde" 的等价信息和之前的例子一样,那么 baseStr = "eed" , "acd""aab",这三个字符串都是等价的,而 "aab"baseStr 的按字典序最小的等价字符串 利用 s1s2 的等价信息,找出并返回 baseStr 的按字典序排列最小的等价字符串。

首先想到用UnionFind解,把所有可以的单词放在一个set,但是由于字典序要小,怎么实现,只需要union的时候,把字典序小的放在父亲位置,那么这个集合的代表节点就是字典序最小的,最后遍历baseStr,把每一个字符用代表节点表示就可以了

class Solution {
    public String smallestEquivalentString(String s1, String s2, String baseStr) {
        char[] str1 = s1.toCharArray();
        char[] str2 = s2.toCharArray();
        int n = str1.length;
        char[] b = baseStr.toCharArray();
        
        UnionFind uf = new UnionFind();
        for(int i = 0; i < n; i++) {
            int a = str1[i] - 'a';
            uf.union(str1[i] - 'a', str2[i] - 'a');
        }
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < b.length; i++) {
            sb.append((char)(uf.find(b[i] - 'a') + 'a'));
        }
        return sb.toString();
    }
}

class UnionFind {
    int N =26;
    int[] parent;
    public UnionFind() {
        parent = new int[N];
        for(int i = 0; i < N; i++) {
            parent[i] = i;
        }
    }
    public int find(int x) {
        while(x != parent[x]) {
            parent[x] = parent[parent[x]];
            x = parent[x];
        }
        return x;
    }
    public void union(int i, int j) {
        int f1 = find(i);
        int f2 = find(j);
        if(f1 != f2) {
            if(f1 < f2) {
                parent[f2] = f1;
            } else {
                parent[f1] = f2;
            }
        }
    }

    public boolean isSameSet(int i, int j) {
        return find(i) == find(j);
    }
}

本文由 mdnice 多平台发布

  • 10
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值