↓快轉到主要內容
  1. LeetCode/

LeetCode 1202: Smallest String With Swaps

·1 分鐘· ·
LeetCode Medium Union-Find
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試: 2025-05-06

  • 總花費時間:10:00.00

解題思路
#

這題要求在一系列允許的交換操作後,回傳字典序最小的字串。
交換的條件是:只有當兩個字元的索引在同一對 pair 中時,才可以互換。
因此,我們可以用並查集(Union Find)來將索引合併為同一群組。
接著,對每個群組中的字元排序,並依照字典序小到大填入結果。

解法
#

class Solution:
    def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
        uf = UF(s)

        for x, y in pairs:
            uf.union(x, y)

        group_map = defaultdict(list)
        for idx in range(len(s)):
            group_map[uf.find(idx)].append(s[idx])
        
        for i in group_map:
            group_map[i] = sorted(group_map[i], reverse=True)

        s = []
        for parent in uf.parent:
            group = uf.find(parent)
            s.append(group_map[group].pop())

        return "".join(s)


class UF:
    def __init__(self, s):
        n = len(s)
        self.parent = [i for i in range(n)]
        self.ranking = [1] * n

    def find(self, num):

        if self.parent[num] != num:
            self.parent[num] = self.find(self.parent[num])

        return self.parent[num]

    def union(self, x, y):
        root_x = self.find(x)
        root_y = self.find(y)

        if root_x == root_y:
            return

        if self.ranking[root_x] > self.ranking[root_y]:
            self.parent[root_y] = self.parent[root_x]
            self.ranking[root_x] += self.ranking[root_y]

        else:
            self.parent[root_x] = self.parent[root_y]
            self.ranking[root_y] += self.ranking[root_x]

收穫
#

遇到的問題
#

相關文章

LeetCode 1319: Number of Operations to Make Network Connected
·1 分鐘
LeetCode Medium Union-Find
LeetCode 解題紀錄
LeetCode 547: Number of Provinces
·2 分鐘
LeetCode Medium Union-Find Dfs
LeetCode 解題紀錄
LeetCode 684: Redundant Connection
·1 分鐘
LeetCode Daily Medium Union-Find
LeetCode 解題紀錄
LeetCode 3493: Properties Graph
·1 分鐘
LeetCode Medium Graph Dfs Union-Find Hash-Map
LeetCode 3493 解題筆記:先把每列轉成 set,兩兩比較交集大小建邊,再數連通塊
LeetCode 695: Max Area of Island
·1 分鐘
LeetCode Medium Array Depth-First-Search Breadth-First-Search Union-Find
LeetCode 695 解題筆記:每遇到一個沒走過的 1 就 DFS 整座島,數格子數,取最大值;格子是整數 1,不是字串
LeetCode 128: Longest Consecutive Sequence
·1 分鐘
LeetCode Medium Array Hash-Table Union-Find
LeetCode 128 解題筆記:放進 set,只從「x - 1 不在 set 裡」的數開始往上數,每個數最多被看兩次,O(n)