Skip to content

20. Valid Parentheses.md #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
127 changes: 127 additions & 0 deletions 20. Valid Parentheses.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
URL: https://leetcode.com/problems/valid-parentheses/description/

# Step 1

- 実装時間: 5分
- 時間計算量: O(n)
- 空間計算量: O(n)

```python
class Solution:
def isValid(self, s: str) -> bool:
opening_parentheses = []
for c in s:
if c in ['(', '{', '[']:

Choose a reason for hiding this comment

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

if c in '({[':

これでも良いですね。Pythonだとstringもsequenceです。
https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str

Strings are immutable sequences of Unicode code points.

opening_parentheses.append(c)
continue
if len(opening_parentheses) == 0:
return False
if c == ')' and opening_parentheses[-1] != '(':
return False
if c == '}' and opening_parentheses[-1] != '{':
return False
if c == ']' and opening_parentheses[-1] != '[':
return False
opening_parentheses.pop()
return True
```

一度間違えた。中途半端に開きっぱなしのケースの考慮漏れ。

- エラーケースを確認して修正した。

```python
class Solution:
def isValid(self, s: str) -> bool:
opening_parentheses = []
for c in s:
if c in ['(', '{', '[']:
opening_parentheses.append(c)
continue
if len(opening_parentheses) == 0:
return False
if c == ')' and opening_parentheses[-1] != '(':
return False
if c == '}' and opening_parentheses[-1] != '{':
return False
if c == ']' and opening_parentheses[-1] != '[':
return False
opening_parentheses.pop()
return len(opening_parentheses) == 0
Copy link

Choose a reason for hiding this comment

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

implicit false を利用してシンプルに書くことをおすすめいたします。
return not opening_parentheses

https://google.github.io/styleguide/pyguide.html#214-truefalse-evaluations

For sequences (strings, lists, tuples), use the fact that empty sequences are false, so if seq: and if not seq: are preferable to if len(seq): and if not len(seq): respectively.

```

# Step 2

- ループ変数`c`について。
- 今回は、ループ変数`i`と同じノリで`c`でいいやと思って使った。でも、ある程度の長さのループで使うし、主役なので名前をつけても良かった。
- https://github.com/konnysh/arai60/pull/6/files#r1843303374
- parenthesesの単数形はparenthesis。
- イギリス英語になるが`bracket`という命名はすべてのカッコを包含できる。
- シンプルに`char`とするパターン
- これは`c`でよさそう

- map(dictionary)を使うやり方。
- 括弧の開閉のペアを`open_to_close`というmapであらかじめ持っておく。
- 拡張性がありそう。
- https://github.com/konnysh/arai60/pull/6/files

- 最後の`len(opening_parentheses) == 0`について。
- > PEP-8 と Google Style Guide は strings, lists, tuples は implicit でということでしたね。
趣味の範囲でしょう。大規模開発などでは周りを見て合わせましょう。
- https://github.com/BumbuShoji/Leetcode/pull/7/files#r1814477339
- なるべくimplicitにする。
- とはいえ、戻り値の型がboolの関数で`return List`とするのがなんとなく好きじゃない。
Copy link

Choose a reason for hiding this comment

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

あ、型が変わるのは良くないですね。bool にキャストするか、頭に !! をつけます。

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。前提を間違えて理解してました。
型が変わるのは良くないというのはとてもしっくりくるので、安心しました。

- 趣味の範囲ということで、`len(opening_parentheses) == 0`を選ぶ。

- stringにシングルクオートを使うか、ダブルクオートを使うか。
- どっちでもいいけど一貫性をもつ。
- https://google.github.io/styleguide/pyguide.html#310-strings
- https://peps.python.org/pep-0008/#string-quotes
- 感覚的にC言語のcharと同じで、1文字だとシングルにしたい。

```python
class Solution:
def isValid(self, s: str) -> bool:
open_to_close = {
'(': ')',
'{': '}',
'[': ']'
}
opening_parentheses = []
for parenthesis in s:
if parenthesis in open_to_close:
opening_parentheses.append(parenthesis)
continue
if not opening_parentheses:
return False
if parenthesis != open_to_close[opening_parentheses[-1]]:
return False
opening_parentheses.pop()
return len(opening_parentheses) == 0
```

# Step 3

- 時間計算量: O(n)
- 空間計算量: O(n)

```python
class Solution:
def isValid(self, s: str) -> bool:
open_to_close = {

Choose a reason for hiding this comment

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

open, closeの代わりにleft, rightも選択肢ですかね。

Brackets are typically deployed in symmetric pairs, and an individual bracket may be identified as a 'left' or 'right' bracket or, alternatively, an "opening bracket" or "closing bracket"

https://en.wikipedia.org/wiki/Bracket

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます!そういう言い方できるの知りませんでした!
wikipedia 的にはleft-rightが標準で、open-closeがalternativeなんですね

'(': ')',
'{': '}',
'[': ']'
}
opening_parentheses = []
for parenthesis in s:
if parenthesis in open_to_close:
opening_parentheses.append(parenthesis)
continue
if not opening_parentheses:
return False
if parenthesis != open_to_close[opening_parentheses[-1]]:
return False
opening_parentheses.pop()
return len(opening_parentheses) == 0
```