博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
1202. 交换字符串中的元素(并查集)
阅读量:4299 次
发布时间:2019-05-27

本文共 2660 字,大约阅读时间需要 8 分钟。

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”

示例 2:

输入:s = “dcab”, pairs = [[0,3],[1,2],[0,2]]
输出:“abcd”
解释:
交换 s[0] 和 s[3], s = “bcad”
交换 s[0] 和 s[2], s = “acbd”
交换 s[1] 和 s[2], s = “abcd”

示例 3:

输入:s = “cba”, pairs = [[0,1],[1,2]]
输出:“abc”
解释:
交换 s[0] 和 s[1], s = “bca”
交换 s[1] 和 s[2], s = “bac”
交换 s[0] 和 s[1], s = “abc”

提示:

1 <= s.length <= 10^5
0 <= pairs.length <= 10^5
0 <= pairs[i][0], pairs[i][1] < s.length
s 中只含有小写英文字母

来源:力扣(LeetCode)

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

代码(含注释题解)

class UnionFind {
//并查集private: int size; vector
parent; vector
rank;public: UnionFind(int _size):size(_size) {
rank.resize(size, 0); parent.resize(size); for(int i = 0; i < size; i++) {
parent[i] = i; } } int find(int x) {
int root = x; while (root != parent[root]) {
root = parent[root]; } while(x != root) {
//路径压缩 int tmp = parent[x]; parent[x] = root; x = tmp; } return root; } void unionSetMerge(int x, int y) {
int px = find(x); int py = find(y); if(px == py) {
return; } if(rank[px] < rank[py]) {
swap(px, py); } parent[py] = px; //按秩合并 if (rank[px] == rank[py]) {
rank[px] += 1; } }};class Solution {
public: string smallestStringWithSwaps(string s, vector
>& pairs) {
if(pairs.size() == 0) {
return s; } int length = s.length(); UnionFind unionFind(length); for(auto& pair: pairs) {
unionFind.unionSetMerge(pair[0], pair[1]); }//基于并查集将字符的**索引值**进行集合划分 unordered_map
> connectedComponents; for(int i = 0; i < length; i++) {
connectedComponents[unionFind.find(i)].emplace_back(s[i]); }//建立索引值所在的集合标识与字符之间的哈希映射 for(auto& [key, arr]: connectedComponents) {
sort(arr.begin(), arr.end(), greater
());//从大到小排序 }//对同一集合内的字符进行排序(这里从大到小,然后逆序输出同一集合内的字符) for(int i = 0; i < length; i++) { int root = unionFind.find(i); //根据当前的索引值,找到所在的集合,然后在集合内找到字典序最小的字符进行替换 s[i] = connectedComponents[root].back(); connectedComponents[root].pop_back(); //字符替换后,集合将删除相应的字符 } return s;//最后将得到排序后的字符串 }};
你可能感兴趣的文章
Objective-C Autorelease Pool 的实现原理
查看>>
编程语言大牛王垠:编程的智慧,带你少走弯路
查看>>
ios指令集以及基于指令集的app包压缩策略
查看>>
iOS开发者的福利 — — iOS9+Xcode7免越狱免证书直接调试
查看>>
3、JavaWeb学习之基础篇—JSP
查看>>
4、JavaWeb学习之基础篇—Session
查看>>
5、JavaWeb学习之基础篇—标签(自定义&JSTL)
查看>>
8、JavaWEB学习之基础篇—文件上传&下载
查看>>
reRender属性的使用
查看>>
href="javascript:void(0)"
查看>>
h:panelGrid、h:panelGroup标签学习
查看>>
f:facet标签 的用法
查看>>
<h:panelgroup>相当于span元素
查看>>
java中append()的方法
查看>>
必学高级SQL语句
查看>>
经典SQL语句大全
查看>>
Eclipse快捷键 10个最有用的快捷键
查看>>
log日志记录是什么
查看>>
<rich:modelPanel>标签的使用
查看>>
<h:commandLink>和<h:inputLink>的区别
查看>>