Lizou punch card 2021.1.11 exchanges elements in the string

Topic:
Give you a string s, and some "index pairs" array pairs in the string, where pairs[i] = [a, b] represent two indexes in the string (numbering starts from 0).
You can swap the characters at any pair of indexes in pairs as many times as you want.
Return the smallest string lexicographically that s can become after several exchanges.
Example 1:
Input: s = “dcab”, pairs = [[0,3],[1,2]]
Output: “bacd”
Explanation:
exchange s[0] and s[3], s = “bcad”
exchange s[1] and s[2], s = "bacd"
Example 2:
Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
Output: " "abcd"
explanation:
exchange s[0] and s[3], s = "bcad"
exchange s[0] and s[2], s = "acbd"
exchange s[1] and s[2], s = " abcd"
Example 3:
Input: s = "cba", pairs = [[0,1],[1,2]]
Output: "abc"
Explanation:
Exchange s[0] and s[1], s = "bca "
Exchange s[1] and s[2], s = "bac"
exchange s[0] and s[1], s = "abc"

Code (and check set):

class DisjointSetUnion {
    
    
private:
    vector<int> f, rank;
    int n;

public:
    DisjointSetUnion(int _n) {
    
    
        n = _n;
        rank.resize(n, 1);
        f.resize(n);
        for (int i = 0; i < n; i++) {
    
    
            f[i] = i;
        }
    }

    int find(int x) {
    
    
        return f[x] == x ? x : f[x] = find(f[x]);
    }

    void unionSet(int x, int y) {
    
    
        int fx = find(x), fy = find(y);
        if (fx == fy) {
    
    
            return;
        }
        if (rank[fx] < rank[fy]) {
    
    
            swap(fx, fy);
        }
        rank[fx] += rank[fy];
        f[fy] = fx;
    }
};

class Solution {
    
    
public:
    string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {
    
    
        DisjointSetUnion dsu(s.length());
        for (auto& it : pairs) {
    
    
            dsu.unionSet(it[0], it[1]);
        }
        unordered_map<int, vector<int>> mp;
        for (int i = 0; i < s.length(); i++) {
    
    
            mp[dsu.find(i)].emplace_back(s[i]);
        }
        for (auto& [x, vec] : mp) {
    
    
            sort(vec.begin(), vec.end(), greater<int>());
        }
        for (int i = 0; i < s.length(); i++) {
    
    
            int x = dsu.find(i);
            s[i] = mp[x].back();
            mp[x].pop_back();
        }
        return s;
    }
};

Guess you like

Origin blog.csdn.net/weixin_45780132/article/details/112495493