|
| 1 | +# Time: O(nlogn) |
| 2 | +# Space: O(n) |
| 3 | + |
| 4 | +import collections |
| 5 | + |
| 6 | + |
| 7 | +class UnionFind(object): |
| 8 | + def __init__(self, n): |
| 9 | + self.set = range(n) |
| 10 | + |
| 11 | + def find_set(self, x): |
| 12 | + if self.set[x] != x: |
| 13 | + self.set[x] = self.find_set(self.set[x]) # path compression. |
| 14 | + return self.set[x] |
| 15 | + |
| 16 | + def union_set(self, x, y): |
| 17 | + x_root, y_root = map(self.find_set, (x, y)) |
| 18 | + if x_root == y_root: |
| 19 | + return False |
| 20 | + self.set[max(x_root, y_root)] = min(x_root, y_root) |
| 21 | + return True |
| 22 | + |
| 23 | + |
| 24 | +class Solution(object): |
| 25 | + def smallestStringWithSwaps(self, s, pairs): |
| 26 | + """ |
| 27 | + :type s: str |
| 28 | + :type pairs: List[List[int]] |
| 29 | + :rtype: str |
| 30 | + """ |
| 31 | + union_find = UnionFind(len(s)) |
| 32 | + for x,y in pairs: |
| 33 | + union_find.union_set(x, y) |
| 34 | + components = collections.defaultdict(list) |
| 35 | + for i in xrange(len(s)): |
| 36 | + components[union_find.find_set(i)].append(s[i]) |
| 37 | + for i in components.iterkeys(): |
| 38 | + components[i].sort(reverse=True) |
| 39 | + result = [] |
| 40 | + for i in xrange(len(s)): |
| 41 | + result.append(components[union_find.find_set(i)].pop()) |
| 42 | + return "".join(result) |
| 43 | + |
| 44 | + |
| 45 | +# Time: O(nlogn) |
| 46 | +# Space: O(n) |
| 47 | +import itertools |
| 48 | +class Solution2(object): |
| 49 | + def smallestStringWithSwaps(self, s, pairs): |
| 50 | + """ |
| 51 | + :type s: str |
| 52 | + :type pairs: List[List[int]] |
| 53 | + :rtype: str |
| 54 | + """ |
| 55 | + def dfs(i, adj, lookup, component): |
| 56 | + lookup.add(i) |
| 57 | + component.append(i) |
| 58 | + for j in adj[i]: |
| 59 | + if j in lookup: |
| 60 | + continue |
| 61 | + dfs(j, adj, lookup, component) |
| 62 | + |
| 63 | + adj = collections.defaultdict(list) |
| 64 | + for i, j in pairs: |
| 65 | + adj[i].append(j) |
| 66 | + adj[j].append(i) |
| 67 | + lookup = set() |
| 68 | + result = list(s) |
| 69 | + for i in xrange(len(s)): |
| 70 | + if i in lookup: |
| 71 | + continue |
| 72 | + component = [] |
| 73 | + dfs(i, adj, lookup, component) |
| 74 | + component.sort() |
| 75 | + chars = sorted(result[k] for k in component) |
| 76 | + for comp, char in itertools.izip(component, chars): |
| 77 | + result[comp] = char |
| 78 | + return "".join(result) |
0 commit comments