Skip to content

Commit ef46b1a

Browse files
authored
Create lexicographically-smallest-equivalent-string.py
1 parent 7aa29e5 commit ef46b1a

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Time: O(nlog*n) ~= O(n), n is the length of S
2+
# Space: O(n)
3+
4+
class UnionFind(object):
5+
def __init__(self, n):
6+
self.set = range(n)
7+
8+
def find_set(self, x):
9+
if self.set[x] != x:
10+
self.set[x] = self.find_set(self.set[x]) # path compression.
11+
return self.set[x]
12+
13+
def union_set(self, x, y):
14+
x_root, y_root = map(self.find_set, (x, y))
15+
if x_root == y_root:
16+
return False
17+
self.set[max(x_root, y_root)] = min(x_root, y_root)
18+
return True
19+
20+
21+
class Solution(object):
22+
def smallestEquivalentString(self, A, B, S):
23+
"""
24+
:type A: str
25+
:type B: str
26+
:type S: str
27+
:rtype: str
28+
"""
29+
union_find = UnionFind(26)
30+
for i in xrange(len(A)):
31+
union_find.union_set(ord(A[i])-ord('a'), ord(B[i])-ord('a'));
32+
result = []
33+
for i in xrange(len(S)):
34+
parent = union_find.find_set(ord(S[i])-ord('a'));
35+
result.append(chr(parent+ord('a')))
36+
return "".join(result)

0 commit comments

Comments
 (0)