|
| 1 | +# Time: O(100 * n^2) = O(n^2) |
| 2 | +# Space: O(1) |
| 3 | + |
| 4 | +class Solution(object): |
| 5 | + def findLexSmallestString(self, s, a, b): |
| 6 | + """ |
| 7 | + :type s: str |
| 8 | + :type a: int |
| 9 | + :type b: int |
| 10 | + :rtype: str |
| 11 | + """ |
| 12 | + def less(s, i, j): |
| 13 | + for k in xrange(len(s)): |
| 14 | + if s[(k+i)%len(s)] != s[(k+j)%len(s)]: |
| 15 | + return s[(k+i)%len(s)] < s[(k+j)%len(s)] |
| 16 | + return False |
| 17 | + |
| 18 | + s = list(s) |
| 19 | + result = s[:] |
| 20 | + even = [False]*10 |
| 21 | + while not even[int(s[0])]: # at most O(10) times |
| 22 | + even[int(s[0])] = True |
| 23 | + odd = [False]*10 |
| 24 | + while not odd[int(s[1])]: # at most O(10) times |
| 25 | + odd[int(s[1])] = True |
| 26 | + best_rotate = 0 |
| 27 | + lookup = [False]*len(s) |
| 28 | + i = b |
| 29 | + while not lookup[i]: # find best rotation, at most O(n) times |
| 30 | + lookup[i] = True |
| 31 | + if less(s, i, best_rotate): # O(n) time |
| 32 | + best_rotate = i |
| 33 | + i = (i+b)%len(s) |
| 34 | + result = min(result, s[best_rotate:] + s[:best_rotate]) |
| 35 | + for k in xrange(1, len(s), 2): # flip odd index |
| 36 | + s[k] = str((int(s[k])+a) % 10) |
| 37 | + if b%2: # if rotate length is odd, even index could be also flipped |
| 38 | + for k in xrange(0, len(s), 2): # flip even index |
| 39 | + s[k] = str((int(s[k])+a) % 10) |
| 40 | + return "".join(result) |
| 41 | + |
| 42 | + |
| 43 | +# Time: O(100 * n^2), at most O(100n) strings and each compare costs O(n) |
| 44 | +# Space: O(n^2) |
| 45 | +import collections |
| 46 | + |
| 47 | + |
| 48 | +class Solution2(object): |
| 49 | + def findLexSmallestString(self, s, a, b): |
| 50 | + """ |
| 51 | + :type s: str |
| 52 | + :type a: int |
| 53 | + :type b: int |
| 54 | + :rtype: str |
| 55 | + """ |
| 56 | + q, lookup, result = collections.deque([s]), {s}, s |
| 57 | + while q: |
| 58 | + curr = q.popleft() |
| 59 | + if curr < result: |
| 60 | + result = curr |
| 61 | + add_a = list(curr) |
| 62 | + for i, c in enumerate(add_a): |
| 63 | + if i%2: |
| 64 | + add_a[i] = str((int(c)+a) % 10) |
| 65 | + add_a = "".join(add_a) |
| 66 | + if add_a not in lookup: |
| 67 | + lookup.add(add_a); |
| 68 | + q.append(add_a) |
| 69 | + rotate_b = curr[b:] + curr[:b] |
| 70 | + if rotate_b not in lookup: |
| 71 | + lookup.add(rotate_b) |
| 72 | + q.append(rotate_b) |
| 73 | + return result |
0 commit comments