LeetCode_UnionFind_1202. Smallest String With Swaps 交换字符串中的元素【并查集】【java】【中等】

目录

一,题目描述

英文描述

中文描述

示例与说明

二,解题思路

三,AC代码

Java

四,解题过程

第一博


一,题目描述

英文描述

You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.

You can swap the characters at any pair of indices in the given pairs any number of times.

Return the lexicographically smallest string that s can be changed to after using the swaps.

中文描述

给你一个字符串 s,以及该字符串中的一些「索引对」数组 pairs,其中 pairs[i] = [a, b] 表示字符串中的两个索引(编号从 0 开始)。

你可以 任意多次交换 在 pairs 中任意一对索引处的字符。

返回在经过若干次交换后,s 可以变成的按字典序最小的字符串。

示例与说明

提示:

  •     1 <= s.length <= 10^5
  •     0 <= pairs.length <= 10^5
  •     0 <= pairs[i][0], pairs[i][1] < s.length
  •     s 中只含有小写英文字母

 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/smallest-string-with-swaps
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二,解题思路

能进行交换的索引看作一个集合。

所有集合中的字符按从小到大的字典顺序排序。

排序后的字符按照原来的索引顺序插入到新的字符数组中即可。

三,AC代码

Java

class Solution {
    int findFather(int[] father, int x) {
        if (father[x] != x) {
            father[x] = findFather(father, father[x]);
        }
        return father[x];
    }
    void unionSet(int[] father, int a, int b) {
        int fa = findFather(father, a);
        int fb = findFather(father, b);
        if (fa != fb) {
            father[fa] = father[fb];
        }
    }
    public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {
        int n = s.length();
        int[] father = new int[n];
        char[] s1 = new char[n];// 存储排序后的字符数组
        for (int i = 0; i < n; i++) {// 初始化并查集
            father[i] = i;
        }
        for (int i = 0; i < pairs.size(); i++) {
            List<Integer> list = pairs.get(i);
            unionSet(father, list.get(0), list.get(1));
        }
        Map<Integer, List<Integer>> record = new HashMap();// 记录各个集合所包含的索引下标
        for (int i = 0; i < n; i++) {
            int fa = findFather(father, i);
            if (!record.containsKey(fa)) {
                record.put(fa, new ArrayList<>());
            }
            record.get(fa).add(i);
        }
        for (Map.Entry<Integer, List<Integer>> entry : record.entrySet()) {
            List<Integer> indexList = entry.getValue();
            List<Character> charList = new ArrayList<>();
            for (int i = 0; i < indexList.size(); i++) {
                charList.add(s.charAt(indexList.get(i)));
            }
            Collections.sort(charList);// 对同一集合的字符集进行排序
            Collections.sort(indexList);// 对同一集合中索引下标进行排序
            for (int i = 0; i < indexList.size(); i++) {
                s1[indexList.get(i)] = charList.get(i);// 将排序后的字符添加到新的字符数组
            }
        }
        return String.valueOf(s1);
    }
}

四,解题过程

第一博

除去语法问题花了点时间,一发如魂

猜你喜欢

转载自blog.csdn.net/qq_41528502/article/details/121417632
今日推荐