|
| 1 | +import itertools |
| 2 | +"Leetcode- https://leetcode.com/problems/backspace-string-compare/ " |
| 3 | +''' |
| 4 | +Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character. |
| 5 | + |
| 6 | +Note that after backspacing an empty text, the text will continue empty. |
| 7 | + |
| 8 | +Example 1: |
| 9 | + |
| 10 | +Input: s = "ab#c", t = "ad#c" |
| 11 | +Output: true |
| 12 | +Explanation: Both s and t become "ac". |
| 13 | +''' |
| 14 | +# Solution-1 |
| 15 | +def backspaceCompare(self, S, T): |
| 16 | + ansS = [] |
| 17 | + for c in S: |
| 18 | + if c == '#': |
| 19 | + if ansS: |
| 20 | + ansS.pop() |
| 21 | + else: |
| 22 | + ansS.append(c) |
| 23 | + |
| 24 | + ansT = [] |
| 25 | + for c in T: |
| 26 | + if c == '#': |
| 27 | + if ansT: |
| 28 | + ansT.pop() |
| 29 | + else: |
| 30 | + ansT.append(c) |
| 31 | + |
| 32 | + return ''.join(ansS) == ''.join(ansT) |
| 33 | + |
| 34 | + #or# |
| 35 | + |
| 36 | + |
| 37 | +def backspaceCompare(self, S, T): |
| 38 | + def build(S): |
| 39 | + ans = [] |
| 40 | + for c in S: |
| 41 | + if c != '#': |
| 42 | + ans.append(c) |
| 43 | + elif ans: |
| 44 | + ans.pop() |
| 45 | + return "".join(ans) |
| 46 | + return build(S) == build(T) |
| 47 | + |
| 48 | +# T:O(M+N) |
| 49 | +# S:O(M+N) |
| 50 | + |
| 51 | +# Solution-2 |
| 52 | +def backspaceCompare(self, s, t): |
| 53 | + l1 = len(s) - 1 |
| 54 | + l2 = len(t) - 1 |
| 55 | + |
| 56 | + while l1 > -1 or l2 > -1: |
| 57 | + # count how many backspace |
| 58 | + count = 0 |
| 59 | + while l1 > -1: |
| 60 | + if s[l1] == "#": |
| 61 | + count += 1 |
| 62 | + l1 -= 1 |
| 63 | + else: |
| 64 | + if count == 0: |
| 65 | + # not backspace, move on |
| 66 | + break |
| 67 | + else: |
| 68 | + # there are backspaces, delete curr char. |
| 69 | + l1 -= 1 |
| 70 | + count -= 1 |
| 71 | + |
| 72 | + count = 0 |
| 73 | + while l2 > -1: |
| 74 | + if t[l2] == "#": |
| 75 | + count += 1 |
| 76 | + l2 -= 1 |
| 77 | + else: |
| 78 | + if count == 0: |
| 79 | + break |
| 80 | + else: |
| 81 | + l2 -= 1 |
| 82 | + count -= 1 |
| 83 | + |
| 84 | + # compare two pointers |
| 85 | + if l1 > -1 and l2 > -1 and s[l1] != t[l2]: |
| 86 | + return False |
| 87 | + |
| 88 | + l1 -= 1 |
| 89 | + l2 -= 1 |
| 90 | + if l1 == l2: |
| 91 | + return True |
| 92 | + else: |
| 93 | + False |
0 commit comments