zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    
  • 相关阅读:
    08测试环境配置_数据库配置
    11等价类
    15状态迁移
    12边界值分析法
    10用例格式
    python的转义字符和原字符
    13数据分析法
    14正交试验
    python软件安装
    cookie的secure属性
  • 原文地址:https://www.cnblogs.com/xgbt/p/14301813.html
Copyright © 2011-2022 走看看