---
# System prepended metadata

title: '**Leetcode筆記(Backspace String Compare)**'
tags: [easy, stack, leetcode]

---

# **Leetcode筆記(Backspace String Compare)**


:::info
:information_source: 題目 : Backspace String Compare, 類型 : stack , 等級 : easy
日期 : 2023/06/05，2024/11/19
:::


### 嘗試
2023/06/05 : 看不懂題目呀
2024/11/19 : something from the furture, you never expected that you worked at Amazon as an intern one year after. Always thanks the persistent and hard-working self in the past. See, you now even know how to code in nice function!
```python
class Solution:
    def backspaceCompare(self, s: str, t: str) -> bool:
        stack_s, stack_t = [], []
        self.check(stack_s, s)
        self.check(stack_t, t)
        return stack_t == stack_s
    
    def check(self, stack, string):
        for c in string:
            if c == "#":
                if stack:
                    stack.pop()
            else:
                stack.append(c)
```

---
### **優化**
刪除鍵（backspace）
題目要求遇到#即刪除前一個字母，最後比看兩個字串有沒有一樣
注意 : 如果是stack的話，基本上都要確認其有沒有存在
時間複雜度O(n)，空間複雜度O(n)

```python
class Solution:
    def backspaceCompare(self, s: str, t: str) -> bool:
        s_stack, t_stack = [], []
        for c in s:
            if c == "#":
                # 題目說若stack中沒東西則不作為
                if s_stack:
                    s_stack.pop()
            else:
                s_stack.append(c)
        
        for c in t:
            if c == "#":
                if t_stack:
                    t_stack.pop()
            else:
                t_stack.append(c)
        
        return s_stack == t_stack
```
---


**:warning: 錯誤語法** 
:::warning

:::


**:thumbsup:學習** 
:::success

:::

**思路**


**講解連結**
https://blog.csdn.net/fuxuemingzhu/article/details/80643408
Provided by. 负雪明烛

###### tags: `stack` `easy` `leetcode`