|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +CREATED AT: 2022年11月10日 |
| 4 | + |
| 5 | +URL: https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/ |
| 6 | + |
| 7 | +GITHUB: https://github.com/Jiezhi/myleetcode |
| 8 | + |
| 9 | +FileName: 1047-RemoveAllAdjacentDuplicatesInString |
| 10 | + |
| 11 | +Difficulty: Easy |
| 12 | + |
| 13 | +Desc: |
| 14 | + |
| 15 | +Tag: |
| 16 | + |
| 17 | +See: |
| 18 | + |
| 19 | +""" |
| 20 | + |
| 21 | + |
| 22 | +class Solution: |
| 23 | + def removeDuplicates(self, s: str) -> str: |
| 24 | + """ |
| 25 | + Runtime: 214 ms, faster than 38.96% |
| 26 | + Memory Usage: 14.8 MB, less than 52.58% |
| 27 | + 1 <= s.length <= 10^5 |
| 28 | + s consists of lowercase English letters. |
| 29 | + """ |
| 30 | + ret = [] |
| 31 | + for c in s: |
| 32 | + if not ret or ret[-1] != c: |
| 33 | + ret.append(c) |
| 34 | + else: |
| 35 | + ret.pop() |
| 36 | + return ''.join(ret) |
| 37 | + |
| 38 | + |
| 39 | +def test(): |
| 40 | + assert Solution().removeDuplicates(s="a") == "a" |
| 41 | + assert Solution().removeDuplicates(s="aa") == "" |
| 42 | + assert Solution().removeDuplicates(s="abbaca") == "ca" |
| 43 | + assert Solution().removeDuplicates(s="azxxzy") == "ay" |
| 44 | + |
| 45 | + |
| 46 | +if __name__ == '__main__': |
| 47 | + test() |
0 commit comments