diff --git a/20. Valid Parentheses/20. Valid Parentheses.md b/20. Valid Parentheses/20. Valid Parentheses.md new file mode 100644 index 0000000..44c4c4f --- /dev/null +++ b/20. Valid Parentheses/20. Valid Parentheses.md @@ -0,0 +1,96 @@ +## STEP 1 +とりあえず書いてみた。 +```python +class Solution: + def isValid(self, s: str) -> bool: + left = ['(', '{', '['] + stack = [] + for i in s: + if i in left: + stack.append(i) + continue + if stack == []: + return False + if i == ')': + if stack.pop() != '(': + return False + if i == '}': + if stack.pop() != '{': + return False + if i == ']': + if stack.pop() != '[': + return False + return stack == [] +``` + +## STEP 2 +- 辞書で対応で明示すると意図が明確だし、コードの分岐が減る。 +- 鍵を開き括弧の方にすると辞書でシンプルに存在確認できてスマート +- pythonの配列の存在内の確認はimplicit falseが一般的らしい。https://google.github.io/styleguide/pyguide.html#2144-decision +- 直接returnで真偽値を書いた方が良い + +```python +class Solution: + def isValid(self, s: str) -> bool: + open_to_close = {'(': ')', '{': '}', '[': ']'} + open_brackets = [] + for c in s: + if c in open_to_close: + open_brackets.append(c) + continue + if open_brackets and open_to_close[open_brackets.pop()] == c: + continue + return False + return not open_brackets +``` + +## STEP 3 +3回書いて練習。 +```python +class Solution: + def isValid(self, s: str) -> bool: + open_to_close = {'(': ')', '{': '}', '[': ']'} + open_brackets = [] + for c in s: + if c in open_to_close: + open_brackets.append(c) + continue + if open_brackets and open_to_close[open_brackets.pop()] == c: + continue + return False + return not open_brackets +``` +ネストが深くなるのはどうかなと思って、一つのif節にしましたが指摘を考慮して別のif節に分けるとこんな感じでしょうか。 +```python +class Solution: + def isValid(self, s: str) -> bool: + open_to_close = {'(': ')', '{': '}', '[': ']'} + open_brackets = [] + for c in s: + if c in open_to_close: + open_brackets.append(c) + continue + if open_brackets: + latest_bracket = open_brackets.pop() + if open_to_close[latest_bracket] == c: + continue + return False + return not open_brackets +``` +ネストを深くせずに分けるとするならばこう書いてもいいんですが、ネストが深くなってもcontinueとreturnが混ざっていない上の方がわかりやすい気がします。 +```python +class Solution: + def isValid(self, s: str) -> bool: + open_to_close = {'(': ')', '{': '}', '[': ']'} + open_brackets = [] + for c in s: + if c in open_to_close: + open_brackets.append(c) + continue + if not open_brackets: + return False + if open_to_close[open_brackets[-1]] != c: + return False + open_brackets.pop() + return not open_brackets +```