第九十五天:力扣 1202题,交换字符串中的元素
地址:leetcode-cn.com/problems/sm…
思路:并查集
var smallestStringWithSwaps = function (s, pairs) {
const len = s.length;
// 初始化
const father = new Array(len).fill(0).map((x, i) => i);
// 查询父类
const find = x => {
if (x === father[x]) {
return father[x];
} else {
father[x] = find(father[x]);
return father[x];
}
}
// 合并
const union = (x, y) => {
father[find(x)] = find(y);
}
// pairs中的关联关系
for (let i = 0; i < pairs.length; i++) {
const [x, y] = pairs[i];
union(x, y);
}
// map记录相同父类下的元素,二维数组表示
const map = new Array(len).fill(0).map(() => new Array());
for (let i = 0; i < len; i++) {
const f = find(father[i]);
map[f].push(s[i]);
}
// 同一个集合下的字符排序,保证字典序最小的靠前
for (let item of map) {
item.sort((a, b) => a.charCodeAt() - b.charCodeAt());
}
let res = '';
for (let i = 0; i < len; i++) {
const f = find(father[i]);
// 每次取集合中首位元素,并删除
res += map[f].shift();
}
return res;
};
执行用时:3140 ms, 在所有 JavaScript 提交中击败了20.00%的用户
内存消耗:68.6 MB, 在所有 JavaScript 提交中击败了40.00%的用户