20. Valid Parentheses#7
Conversation
9c18bfc to
7156015
Compare
| def isValid(self, s: str) -> bool: | ||
| stack = deque() | ||
| for ch in s: | ||
| if ch in self.OPEN_TO_CLOSE: |
There was a problem hiding this comment.
[nits]
elif 節との対応を考えて、あえて
| if ch in self.OPEN_TO_CLOSE: | |
| if ch in self.OPEN_TO_CLOSE.keys(): |
と書くのもアリかと思いました。
| elif ch in self.OPEN_TO_CLOSE.values(): | ||
| if not stack: | ||
| return False | ||
| prev_open = stack.pop() |
There was a problem hiding this comment.
個人的には、previousってcurrent, nextのような相対的な位置関係の文脈で使われる印象があります。もちろん時間軸の意味でも通じるのでしょうが、そうであれば last の方がより自然に思いました。
| prev_open = stack.pop() | |
| last_opened = stack.pop() |
| ``` | ||
| - https://discord.com/channels/1084280443945353267/1225849404037009609/1231646037077131315 | ||
| - > 私は、open_to_close でデータは持ちたいです。文字列にカッコ以外が来たときに落ちないで欲しいからです。 | ||
| - 理解できていない。。。(close_to_openだとしても(*1)のように閉、開、その他で場合分けできそう。。。) |
There was a problem hiding this comment.
どんなデータの持ち方でも十分に情報があるならばデータを変形をすればいいわけですから理屈上できますが、in x.values() は全部集めた後に線形で探すというのを毎回しているのでできればしたくない動きだという背景があります。
もっとも、要素数が20くらいならば線形でも速いのですが。
| - https://docs.python.org/3/library/collections.html#collections.deque | ||
| - dequeを使っても実装できる | ||
| - リストとの違い、だれかがエンジニアリングをして課題を解決してくれた | ||
| - > Though list objects support similar operations, they are optimized for fast fixed-length operations and incur O(n) memory movement costs for pop(0) and insert(0, v) operations which change both the size and position of the underlying data representation. |
There was a problem hiding this comment.
今回の問題では最後尾にしかアクセスせず、ここで挙げられているデメリットは問題ではないので、私だったらlistを使用するかと思いますが、趣味の範囲内かと思います。個人的にはdequeを見ると、両端へのアクセスがあるのかなと最初は予測しますが、身の回りの感覚を想像するに、私がちょっと考えすぎなタイプなのだと思うので、単なる参考まで。
| stack = deque() | ||
| for ch in s: | ||
| if ch in self.OPEN_TO_CLOSE: | ||
| stack.append(ch) |
There was a problem hiding this comment.
私はstep 1のように、if-elif-else ではなく、continue / return で早めに処理を抜けてもらえた方が、関係のない処理を読まなくて良くなるので嬉しいですね(if-elseだと最後に何か共通の処理がないか確認する必要がある)。また、ontinue / return の方が脳内フローチャートも単純になるような感覚があります。
この問題: 20. Valid Parentheses
次の問題: 206. Reverse Linked List