diff --git a/844. Backspace String Compare.md b/844. Backspace String Compare.md new file mode 100644 index 0000000..160d283 --- /dev/null +++ b/844. Backspace String Compare.md @@ -0,0 +1,87 @@ +# 844. Backspace String Compare +https://leetcode.com/problems/backspace-string-compare/ + +# 1st +#があると一つ前の文字を消去、最終的に残ったものを比較ということで、 +最後に入れたものを削除しやすいスタックを選択 + +```python +class Solution: + def backspaceCompare(self, s: str, t: str) -> bool: + s_stack = [] + t_stack = [] + + for s_1 in s: + if s_1 != '#': + s_stack.append(s_1) + elif len(s_stack) != 0: + s_stack.pop() + for t_1 in t: + if t_1 != '#': + t_stack.append(t_1) + elif len(t_stack) != 0: + t_stack.pop() + + + if len(s_stack) != len(t_stack): + return False + + loop_cnt = len(s_stack) + while loop_cnt > 0: + if s_stack.pop() != t_stack.pop(): + return False + loop_cnt -= 1 + + return True +``` + +# 2nd・3rd +s1・t1をcharに変更しました +```python +class Solution: + def backspaceCompare(self, s: str, t: str) -> bool: + s_stack = [] + t_stack = [] + + for char in s: + if char != '#': + s_stack.append(char) + elif len(s_stack) != 0: + s_stack.pop() + for char in t: + if char != '#': + t_stack.append(char) + elif len(t_stack) != 0: + t_stack.pop() + + + if len(s_stack) != len(t_stack): + return False + + loop_cnt = len(s_stack) + while loop_cnt > 0: + if s_stack.pop() != t_stack.pop(): + return False + loop_cnt -= 1 + + return True + + +``` + +# 4th レビューを基に再構築 +```python +class Solution: + def backspaceCompare(self, s: str, t: str) -> bool: + def backspace_string(x): + x_stack = [] + for c in x: + if c == '#': + if x_stack: + x_stack.pop() + continue + x_stack.append(c) + return x_stack + + return backspace_string(s) == backspace_string(t) +```