20. valid parentheses#5
Open
lightbanana wants to merge 7 commits into
Open
Conversation
lightbanana
commented
Jul 9, 2026
Owner
- 今回解いた問題:20. Valid Parentheses(https://leetcode.com/problems/valid-parentheses/description/?envType=problem-list-v2&envId=xo2bgr0r)
- 次に解く問題:703. Kth Largest Element in a Stream(https://leetcode.com/problems/kth-largest-element-in-a-stream/?envType=problem-list-v2&envId=xo2bgr0r)
h-masder
reviewed
Jul 9, 2026
|
|
||
| ## Step 1 | ||
| ### 考えたこと | ||
| スタックに([{が来るたびに一つずつ積んでいって、)]}が来るたびに一つずつスタックからpopしていく。スタックの名前がスタックなのは少し嫌だと思ったが、他に思いつかなかったのでとりあえずstackにした。時間計算量はO(n)、空間計算量もO(n)。 |
There was a problem hiding this comment.
Owner
Author
There was a problem hiding this comment.
ありがとうございます!これから意識するようにしてみます。
Pythonでのこのような単純な処理であれば1回0.1us-1us程度と考えて、O(n)でsのlengthが最大10^4のため、最悪でも100us-1000usの範囲内と見積もるイメージでやってみようと思います。
実際にsのlengthを最大にして計測したところ、260usだったため見積もりの範囲内でした。
h-masder
reviewed
Jul 9, 2026
| last = open_brackets.pop() | ||
| if open_to_close[last] != c: | ||
| return False | ||
| return (len(open_brackets) == 0) |
There was a problem hiding this comment.
There was a problem hiding this comment.
PEP 8でも同様の記述がなされていますね。
https://peps.python.org/pep-0008/
For sequences, (strings, lists, tuples), use the fact that empty sequences are false:
Correct:
if not seq: if seq:Wrong:
if len(seq): if not len(seq):
Owner
Author
There was a problem hiding this comment.
ありがとうございます。PEP 8のほうも確認させていただきました。何度か指摘されているので、まさにソフトウェアエンジニアの常識の典型例なのかなと感じています。
h-masder
reviewed
Jul 9, 2026
| if not last or bracket != open_to_close[last]: | ||
| return False | ||
| return (len(open_brackets) == 1) # Check only the sentinel left | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.