File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def smallestStringWithSwaps (self , s : str , pairs : List [List [int ]]) -> str :
3
+ def dfs (node , subgraph ):
4
+ if node not in seen :
5
+ seen .add (node )
6
+ subgraph .append (node )
7
+ for neighbor in graph [node ]:
8
+ dfs (neighbor , subgraph )
9
+
10
+ seen = set ()
11
+ graph = defaultdict (list )
12
+ for src , dest in pairs :
13
+ graph [src ].append (dest )
14
+ graph [dest ].append (src )
15
+
16
+ res = list (s )
17
+ for node in graph .keys ():
18
+ if len (seen ) == len (res ):
19
+ return '' .join (res )
20
+
21
+ sub_graph = []
22
+ dfs (node , sub_graph )
23
+
24
+ if len (sub_graph ) != 0 :
25
+ sub_graph = sorted (list (set (sub_graph )))
26
+ sub_char = sorted ([s [i ] for i in sub_graph ])
27
+
28
+ for x , y in zip (sub_graph , sub_char ):
29
+ res [x ] = y
30
+
31
+ return '' .join (res )
You can’t perform that action at this time.
0 commit comments