|
| 1 | +# https://leetcode.com/problems/is-subsequence/ |
| 2 | + |
| 3 | +import timeit |
| 4 | + |
| 5 | + |
| 6 | +# Runtime: 48 ms, faster than 57.69% of Python3 online submissions for Is Subsequence. |
| 7 | +# Memory Usage: 13.9 MB, less than 44.81 % of Python3 online submissions for Is Subsequence. |
| 8 | +class Solution: |
| 9 | + def isSubsequence(self, s: str, t: str) -> bool: |
| 10 | + if len(s) > len(t): |
| 11 | + return False |
| 12 | + if not s: |
| 13 | + return True |
| 14 | + pointer = 0 |
| 15 | + for char in t: |
| 16 | + if pointer == len(s): |
| 17 | + return True |
| 18 | + if char == s[pointer]: |
| 19 | + pointer += 1 |
| 20 | + return pointer == len(s) |
| 21 | + |
| 22 | + |
| 23 | +def test(): |
| 24 | + executor = [ |
| 25 | + {'executor': Solution, 'title': 'Solution', }, |
| 26 | + ] |
| 27 | + tests = [ |
| 28 | + ["", "", True], |
| 29 | + ["", "abc", True], |
| 30 | + ["b", "abc", True], |
| 31 | + ["d", "abcabcabcabcabcd", True], |
| 32 | + ["d", "abcabcabcabcabc", False], |
| 33 | + ["abc", "ahbgdc", True], |
| 34 | + ["axc", "ahbgdc", False], |
| 35 | + ] |
| 36 | + for e in executor: |
| 37 | + start = timeit.default_timer() |
| 38 | + for _ in range(int(float('1'))): |
| 39 | + for t in tests: |
| 40 | + sol = e['executor']() |
| 41 | + result = sol.isSubsequence(t[0], t[1]) |
| 42 | + expected = t[2] |
| 43 | + assert result == expected, f'{result} != {expected} for {t[0]}:{t[1]} using {e["title"]} solution' |
| 44 | + used = str(round(timeit.default_timer() - start, 5)) |
| 45 | + result = "{0:20}{1:10}{2:10}".format(e['title'], used, "seconds") |
| 46 | + print(f"\033[92m» {result}\033[0m") |
| 47 | + |
| 48 | + |
| 49 | +test() |
0 commit comments