ID | Title | Difficulty | |
---|---|---|---|
Loading... |
1202. Smallest String With Swaps
Medium
LeetCode
Hash Table, String, Depth-First Search, Breadth-First Search, Union Find
Problem
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.
Example 1:
Input: s = "dcab", pairs = [[0,3],[1,2]]
Output: "bacd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[1] and s[2], s = "bacd"
Example 2:
Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
Output: "abcd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[0] and s[2], s = "acbd"
Swap s[1] and s[2], s = "abcd"
Example 3:
Input: s = "cba", pairs = [[0,1],[1,2]]
Output: "abc"
Explaination:
Swap s[0] and s[1], s = "bca"
Swap s[1] and s[2], s = "bac"
Swap s[0] and s[1], s = "abc"
Constraints:
1 <= s.length <= 10^5
0 <= pairs.length <= 10^5
0 <= pairs[i][0], pairs[i][1] < s.length
s
only contains lower case English letters.
Code
class Solution {
public class UnionFind {
int[] parents;
int[] ranks;
public UnionFind(int n) {
parents = new int[n];
ranks = new int[n];
for (int i = 0; i < n; i++) {
parents[i] = i;
ranks[i] = 1;
}
}
public boolean union(int x, int y) {
int xParent = find(x);
int yParent = find(y);
if (xParent == yParent) return false;
if (ranks[xParent] > ranks[yParent]) {
parents[yParent] = xParent;
} else if (ranks[xParent] < ranks[yParent]) {
parents[xParent] = yParent;
} else {
parents[yParent] = xParent;
ranks[xParent]++;
}
return true;
}
public int find(int node) {
if(node == parents[node]) return node;
return find(parents[node]);
}
}
public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {
UnionFind node = new UnionFind(s.length());
for(List<Integer> pair : pairs) {
node.union(pair.get(0), pair.get(1));
}
Map<Integer, PriorityQueue<Character>> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
int parent = node.find(i);
if(!map.containsKey(parent)) {
map.put(parent, new PriorityQueue<>());
}
map.get(parent).offer(s.charAt(i));
}
StringBuilder res = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
res.append(map.get(node.find(i)).poll());
}
return res.toString();
}
}
按 <- 键看上一题!
1201. Ugly Number III
按 -> 键看下一题!
1204. Last Person to Fit in the Bus