-
Notifications
You must be signed in to change notification settings - Fork 0
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
Add 20. Valid Parentheses.md #6
base: main
Are you sure you want to change the base?
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
該当資料が充実していて、コードも読みやすいし指摘するところが思いつかないので敢えていうなら辞書部分をリストにした解法とかどうですか
open_brackets = [...]
close_brackets = [...]
みたいな感じで
open_bracket_stack = [] | ||
for bracket in s: | ||
if bracket in open_to_close: | ||
open_bracket_stack.append(bracket) | ||
continue | ||
|
||
if (not open_bracket_stack \ | ||
or open_to_close[open_bracket_stack[-1]] != bracket): | ||
return False | ||
|
||
open_bracket_stack.pop() | ||
return not open_bracket_stack |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
open_bracket_stack = [] | |
for bracket in s: | |
if bracket in open_to_close: | |
open_bracket_stack.append(bracket) | |
continue | |
if (not open_bracket_stack \ | |
or open_to_close[open_bracket_stack[-1]] != bracket): | |
return False | |
open_bracket_stack.pop() | |
return not open_bracket_stack | |
stack = [] | |
for bracket in s: | |
if bracket in open_to_close: | |
stack.append(bracket) | |
continue | |
elif not stack or open_to_close[stack.pop()] != bracket: | |
return False | |
return not stack |
popと条件分岐を同時にできるのでこのような書き方もありかなと思いました。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
良いと思います。
if bracket in open_to_close: | ||
open_bracket_stack.append(bracket) | ||
continue | ||
if (open_bracket_stack |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
自分は2つのif文に分けるかなと思いますが、好みかもしれないです。
``` | ||
|
||
- `open_bracket_stack`という名前はopen_bracketしか入らないこと・初期化時にリストを代入しているが用法としてはstackとして使うことがわかるようにした。 | ||
- `or open_to_close[open_bracket_stack[-1]] != bracket):`はインデントして、下の部分が条件式ではないことを明確にした。[PEP8](https://peps.python.org/pep-0008/#indentation)では特に指定がなかった。 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
こういうフォーマットは、それなりに幅があって正解がないものであるということです。
autoformatter たとえば black などを参考にするのも一つでしょう。
https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#how-black-wraps-lines
いいと思います! |
問題
https://leetcode.com/problems/valid-parentheses/