Conversation
| return False | ||
|
|
||
| open_bracket = stack.pop() | ||
| if not bracket_pairs[open_bracket] == c: |
There was a problem hiding this comment.
ここは素直に
if bracket_pairs[open_bracket] != c:で良いのではないでしょうか。
There was a problem hiding this comment.
奇妙な書き方をしていました。ご指摘ありがとうございます。
| if c in bracket_pairs: | ||
| stack.append(c) | ||
| else: | ||
| if not stack: |
There was a problem hiding this comment.
ここはネストを深くするよりcontinueで切った方が読みやすいなと感じます。
if c in bracket_pairs:
stack.append(c)
continue
if not stack:There was a problem hiding this comment.
ありがとうございます。early continueしてみます。
| @@ -0,0 +1,20 @@ | |||
| class Solution: | |||
| def isValid(self, s: str) -> bool: | |||
| stack = [] | |||
There was a problem hiding this comment.
何を入れるstackなのかわかる命名だと良いかもしれません。
brackets_stack とかですかね。
| bracket_pairs = { | ||
| '(': ')', | ||
| '{': '}', | ||
| '[': ']', | ||
| } |
There was a problem hiding this comment.
いい名前ですね。open_to_close 真似させていただきます。
| if c in bracket_pairs: | ||
| stack.append(c) | ||
| else: | ||
| if not stack: | ||
| return False | ||
|
|
||
| open_bracket = stack.pop() | ||
| if not bracket_pairs[open_bracket] == c: | ||
| return False |
There was a problem hiding this comment.
cだけ見るより、「stackのtopと合わせてペアができるか」に注目したほうが条件分岐が少なくなっていいのではと思いました。
(Pythonに詳しくなく、動くコードかは怪しいです...)
| if c in bracket_pairs: | |
| stack.append(c) | |
| else: | |
| if not stack: | |
| return False | |
| open_bracket = stack.pop() | |
| if not bracket_pairs[open_bracket] == c: | |
| return False | |
| top = stack[-1] | |
| is_match = False | |
| match (top, c): | |
| case ('(', ')'): | |
| is_match = True | |
| case ('{', '}'): | |
| is_match = True | |
| case ('[', ']'): | |
| is_match = True | |
| if is_match: | |
| stack.pop() | |
| else: | |
| stack.append(c) | |
There was a problem hiding this comment.
コメントありがとうございます。
これは好みの問題ですが、stackに閉じカッコを入れる場合(上のコードで c in [')', '}', ']'] かつ is_match がfalse)は、その時点で全体としてのカッコ列の整合性が崩れるので return false すると頭の中のスタックが解放される感じがします。
例えば (}((((())))) とあったときに、3文字目以降は見なくていいよね、という感じです。
There was a problem hiding this comment.
@kazukiii
なるほどです。場合によっては早めにinvalid判定できるんですね
ありがとうございます〜
問題へのリンク
https://leetcode.com/problems/valid-parentheses/description/
次に解く問題
206. Reverse Linked List
README.mdへ頭の中の言語化と記録をしています。