1202. 交换字符串中的元素 并查集

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

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

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

示例 1:

输入:s = "dcab", pairs = [[0,3],[1,2]]
输出:"bacd"
解释:
交换 s[0] 和 s[3], s = "bcad"
交换 s[1] 和 s[2], s = "bacd"

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

class Solution {
public:
    unordered_map <int, int> fa;
    unordered_map <int, int> rank;

    int find(int x) {
        if (!fa.count(x)) {
            fa[x] = x;
            rank[x] = 1;
        }
        return fa[x] == x ? fa[x] : fa[x] = find(fa[x]);
    }

    bool same(int x, int y) {
        return find(x) == find(y);
    }

    void unit(int x, int y) {
        int xx = find(x);
        int yy = find(y);
        if (same(xx, yy)) {
            return;
        }
        if (rank[xx] < rank[yy]) {
            swap(xx, yy);
        }
        rank[xx] += rank[yy];
        fa[yy] = xx;
    }

    string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {

        int n = pairs.size();

        unordered_map <int, vector<char>> mp;

        for (auto pair : pairs) {
            unit(pair[0], pair[1]);
        }

        for (int i = 0; i < s.size(); i++) {
            mp[find(i)].emplace_back(s[i]);
        }

        for (auto& [x, vec] : mp) {
            sort(vec.begin(), vec.end(), greater<int>());
        }

        for (int i = 0; i < s.size(); i++) {
            int x = find(i);
            s[i] = mp[x].back();
            mp[x].pop_back();
        }

        return s;
    }
};
posted @ 2021-01-20 11:12  _西瓜不甜  阅读(63)  评论(0编辑  收藏  举报