|
| 1 | +# 1544. Make The String Great |
| 2 | +# 🟢 Easy |
| 3 | +# |
| 4 | +# https://leetcode.com/problems/make-the-string-great/ |
| 5 | +# |
| 6 | +# Tags: String - Stack |
| 7 | + |
| 8 | +import timeit |
| 9 | + |
| 10 | + |
| 11 | +# Iterate over the elements of the input string pushing them into a |
| 12 | +# stack, if the element that we visit is the uppercase or lowercase |
| 13 | +# counterpart of the last element on the stack, pop that element. |
| 14 | +# |
| 15 | +# Time complexity: O(n) - Where n is the number of characters in the |
| 16 | +# input. |
| 17 | +# Space complexity: O(n) - The stack could have n elements where n is |
| 18 | +# the number of characters of the input. |
| 19 | +# |
| 20 | +# Runtime: 53 ms, faster than 76.90% |
| 21 | +# Memory Usage: 13.8 MB, less than 61.93% |
| 22 | +class StackPushPop: |
| 23 | + def makeGood(self, s: str) -> str: |
| 24 | + stack = [] |
| 25 | + for c in s: |
| 26 | + if stack and ( |
| 27 | + (c.islower() and c.upper() == stack[-1]) |
| 28 | + or (c.isupper() and c.lower() == stack[-1]) |
| 29 | + ): |
| 30 | + stack.pop() |
| 31 | + else: |
| 32 | + stack.append(c) |
| 33 | + return "".join(stack) |
| 34 | + |
| 35 | + |
| 36 | +# Similar approach but simplify the if statement using character's ASCII |
| 37 | +# values. |
| 38 | +# |
| 39 | +# Time complexity: O(n) - Where n is the number of characters in the |
| 40 | +# input. |
| 41 | +# Space complexity: O(n) - The stack could have n elements where n is |
| 42 | +# the number of characters of the input. |
| 43 | +# |
| 44 | +# Runtime: 24 ms, faster than 99.91% |
| 45 | +# Memory Usage: 13.8 MB, less than 61.93% |
| 46 | +class StackAndOrd: |
| 47 | + def makeGood(self, s: str) -> str: |
| 48 | + stack = [] |
| 49 | + for c in s: |
| 50 | + if stack and abs(ord(c) - ord(stack[-1])) == 32: |
| 51 | + stack.pop() |
| 52 | + else: |
| 53 | + stack.append(c) |
| 54 | + return "".join(stack) |
| 55 | + |
| 56 | + |
| 57 | +def test(): |
| 58 | + executors = [ |
| 59 | + StackPushPop, |
| 60 | + StackAndOrd, |
| 61 | + ] |
| 62 | + tests = [ |
| 63 | + ["s", "s"], |
| 64 | + ["Pp", ""], |
| 65 | + ["abBAcC", ""], |
| 66 | + ["leEeetcode", "leetcode"], |
| 67 | + ] |
| 68 | + for executor in executors: |
| 69 | + start = timeit.default_timer() |
| 70 | + for _ in range(1): |
| 71 | + for col, t in enumerate(tests): |
| 72 | + sol = executor() |
| 73 | + result = sol.makeGood(t[0]) |
| 74 | + exp = t[1] |
| 75 | + assert result == exp, ( |
| 76 | + f"\033[93m» {result} <> {exp}\033[91m for" |
| 77 | + + f" test {col} using \033[1m{executor.__name__}" |
| 78 | + ) |
| 79 | + stop = timeit.default_timer() |
| 80 | + used = str(round(stop - start, 5)) |
| 81 | + cols = "{0:20}{1:10}{2:10}" |
| 82 | + res = cols.format(executor.__name__, used, "seconds") |
| 83 | + print(f"\033[92m» {res}\033[0m") |
| 84 | + |
| 85 | + |
| 86 | +test() |
0 commit comments