Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions 20. Valid Parentheses/20. Valid Parentheses.md
Original file line number Diff line number Diff line change
@@ -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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

二つ目を別のif節の中に入れたほうが好みです(副作用のあるpopして大丈夫なの?と不安になりました、結局その場合 continueを踏んでFalseを返すのだと、続きを読めばわかりますが)

別のif節でも、stack[-1]で先頭を確認してから pop するほうが素直かな、と

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

なるほど、popがif節の中に現れるとちょっと不安ですね。ありがとうございます。

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
```