Conversation
| else: | ||
| stack.append(char) | ||
|
|
||
| return stack == [] |
There was a problem hiding this comment.
こちらは空のリストはfalseであることを利用して以下のようにも書けますね
| return stack == [] | |
| return not stack |
ご参考までにGoogleのスタイルガイドではこの書き方が推奨されているようです
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.
https://google.github.io/styleguide/pyguide.html#2144-decision
| stack = [] | ||
| bracket_pairs = { "}": "{", "]": "[", ")": "("} | ||
|
|
||
| for char in s: |
There was a problem hiding this comment.
charはC/C++の予約語なので気にする人もいるかもしれません
https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0#heading=h.34fedgfeaxcw
| class Solution: | ||
| def isValid(self, s: str) -> bool: | ||
| stack = [] | ||
| bracket_pairs = { "}": "{", "]": "[", ")": "("} |
There was a problem hiding this comment.
この書き方はぱっと見で対応が取れているか分かりづらいので、開き括弧→閉じ括弧にしてスタックからポップした開き括弧をこの対応に入れて一致を見るという方法もあります
There was a problem hiding this comment.
ありがとうございます。たしかに対応見にくいですね、!
こちらのコミットで仰るやり方も試してみました。addc28c
Valid Parentheses/memo.md
Outdated
|
|
||
| せっかくなのでナイーブな方法を考えてみた。 | ||
| 全部 replace すればいいかという安易な考えでコーディングしてみた。 | ||
| Brute Force で解いてみても計算量は O(N) なので悪くはないかなとは思った。(正規表現でマッチングしているのでもちろん計算量がアルゴリズムの選択肢になるとは思っていないです。) |
There was a problem hiding this comment.
validな文字列だと括弧のペアがN/2あるのでループはN/2回回り、そしてinやreplaceで文字列の長さ分は計算量がかかりそうなのでO(N^2)かかるんじゃないかという気がしました
There was a problem hiding this comment.
たしかに、最悪の場合O(N) の処理が O(N/2) 回繰り返されるので O(N^2) ですね、!
考えが足りてなかったです、ありがとうございます!
|
|
||
| for char in s: | ||
| if char in bracket_pairs: | ||
| if len(stack) > 0 and stack[-1] == bracket_pairs[char]: |
| class Solution: | ||
| def isValid(self, s: str) -> bool: | ||
| stack = [] | ||
| bracket_pairs = { ")": "(", "]": "[", "}": "{"} |
There was a problem hiding this comment.
ここの変数名、close_to_openとかにすると対応関係がわかりやすくなるかなと感じました。
辞書やタプルの場合は、x_to_y のような名前の付け方があるらしいです。
https://github.com/irohafternoon/LeetCode/pull/11/files#r2024946024
| s = s.replace("{}", "") | ||
| s = s.replace("[]", "") | ||
|
|
||
| return s == "" |
There was a problem hiding this comment.
return not sと、 Implicit false を使った書き方はいかがでしょうか?
参考までにスタイルガイドへのリンクを貼ります。
https://google.github.io/styleguide/pyguide.html#2144-decision
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.
上記のスタイルガイドは唯一絶対のルールではなく、複数あるスタイルガイドの一つに過ぎないということを念頭に置くことをお勧めします。また、所属するチームにより何が良いとされているかは変わります。自分の中で良い書き方の基準を持ちつつ、チームの平均的な書き方で書くことをお勧めいたします。
|
|
||
| for char in s: | ||
| if char in bracket_pairs: | ||
| if len(stack) > 0 and stack[-1] == bracket_pairs[char]: |
There was a problem hiding this comment.
if stack and stack[-1] == bracket_pairs[char]:と書いたほうがシンプルだと思います。
問題: https://leetcode.com/problems/valid-parentheses/description/