题目如下:

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.

解题思路:可以用并查集把所有可以交换的下标分成若干个组,每个组里面的下标都是可以互相交换的,这样只需要把每个组中下标所对应的最小字符放到最小下标的位置,次小值放到次小下标的位置...最大值放到最大下标的位置,即可得到结果。

代码如下:

class Solution(object):
def smallestStringWithSwaps(self, s, pairs):
"""
:type s: str
:type pairs: List[List[int]]
:rtype: str
"""
parent = [i for i in range(len(s))]
def find(v):
if v == parent[v]:
return v
return find(parent[v])
def union(v1,v2):
p1 = find(v1)
p2 = find(v2)
if p1 > p2:
parent[p1] = p2
else:
parent[p2] = p1 for (i,j) in pairs:
union(i,j)
dic_val = {}
for i in range(len(parent)):
p = find(i)
parent[i] = p
dic_val[p] = dic_val.setdefault(p,'') + s[i] for key in dic_val.iterkeys():
dic_val[key] = ''.join(sorted(list(dic_val[key]))) res = ''
for i in parent:
res += dic_val[i][0]
dic_val[i] = dic_val[i][1:] return res

【leetcode】1202. Smallest String With Swaps的更多相关文章

  1. 【LeetCode】988. Smallest String Starting From Leaf 解题报告(C++ & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 题目地址:https://le ...

  2. 【leetcode】988. Smallest String Starting From Leaf

    题目如下: Given the root of a binary tree, each node has a value from 0 to 25representing the letters 'a ...

  3. 【LeetCode】481. Magical String 解题报告(Python)

    [LeetCode]481. Magical String 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http:/ ...

  4. 【LeetCode】880. Decoded String at Index 解题报告(Python)

    [LeetCode]880. Decoded String at Index 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博 ...

  5. 【LeetCode】#344 Reverse String

    [Question] Write a function that takes a string as input and returns the string reversed. Example: G ...

  6. 【leetcode】1081. Smallest Subsequence of Distinct Characters

    题目如下: Return the lexicographically smallest subsequence of text that contains all the distinct chara ...

  7. 【LeetCode】344. Reverse String 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 新构建字符串 原地翻转 日期 题目地址:https://lee ...

  8. 【LeetCode】1023. Binary String With Substrings Representing 1 To N 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  9. 【LeetCode】1022. Smallest Integer Divisible by K 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

随机推荐

  1. gitlab ssh 免密登录

    打开本地git   使用 ssh-keygen 工具 输入命令  ssh-keygen -t rsa -C '你的邮箱账号' 接下来输入密码 确认密码 找到目录 找到公钥 在 gitlab 用户设置  ...

  2. USACO2.1 Hamming Codes【枚举+二进制处理+输出格式+题意理解】

    这道题加了2个看起来奇奇怪怪的$tag$ 1.输出格式:不得不说这个格式输出很恶心,很像$UVA$的风格,细节稍微处理不好就会出错. 因为这个还$WA$了一次: ,m=n; ) { ;i<=t+ ...

  3. 模板中用url_for的好处

    from flask import Flask,render_template app = Flask(__name__) @app.route('/') def index(): return re ...

  4. Python 正则匹配网页内的IP地址及端口号

    #!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-08-30 20:38:23 # @Author : EnderZhou (z ...

  5. 反复横跳的瞄准线!从向量计算说起!基于射线检测的实现!Cocos Creator!

    最近有小伙伴问我瞄准线遇到各种形状该怎么处理?如何实现反复横跳的瞄准线?最近刚好在<Cocos Creator游戏开发实战>中看到物理系统有一个射线检测,于是,基于这个射线检测,写了一个反 ...

  6. [转帖]C#中字典集合HashTable、Dictionary、ConcurrentDictionary三者区别

    C#中字典集合HashTable.Dictionary.ConcurrentDictionary三者区别 https://blog.csdn.net/yinghuolsx/article/detail ...

  7. HDU 6175 算术

    题目大意 求 $\sum_{i = 1}^{n} \sum_{j = 1}^{m} \mu(\lcm(i, j))$ . $ 1 \le n, m \le 10^6 $ . 分析 不妨设 $ n \l ...

  8. Linux的用户与用户组(权限管理)

    linux用户与用户.权限管理 用户管理: 1.useradd 创建用户 -c 指定用户描述 -d 指定家目录 默认家目录 /home下同名的目录 -g 指定主组 -G 指定附加组 [注意:一个用户主 ...

  9. Fire Net HDU - 1045 (二分图匹配)

    题意: 给出一张图,图中'X'表示wall,'.'表示空地,可以放置blockhouse同一条直线上只能有一个blockhouse,除非有wall 隔开,问在给出的图中最多能放置多少个blockhou ...

  10. 解决Asp.Net core 控制台出现乱码的情况

    将控制台的编码页修改成Unicode,在运行程序或者在程序里加一行Console.OutputEncoding = Encoding.Unicode; Console.OutputEncoding = ...