Skip to content

Conversation

@KTakao01
Copy link
Owner

@KTakao01 KTakao01 commented Oct 19, 2025

問題リンク:https://leetcode.com/problems/valid-parentheses/description/

3、4ヶ月ぶりに解いたところ、初回の回答(leetcodeの模範回答)とは別の方法で解いてしまったため、改めてレビューをお願いしたいです。

Summary by CodeRabbit

  • Documentation
    • 括弧(ペア)検証に関するドキュメントを改善しました。冗長な下書きを整理し、より簡潔で正確な実装例を追加。入力検証の挙動と終了条件を明確化して、理解しやすさと再現性を向上させました。

@KTakao01 KTakao01 self-assigned this Oct 19, 2025
@coderabbitai
Copy link

coderabbitai bot commented Oct 19, 2025

Walkthrough

スタックとマップを使った単一パスの括弧妥当性検証 isValid の具体的実装が追加され、開き括弧をスタックに積み、閉じ括弧でスタックトップと対応を照合する流れを明示的に実装しています(最終的にスタックが空であることを確認)。

Changes

コホート / ファイル(s) 変更概要
括弧検証アルゴリズムの実装
20.ValidParentheses_251019.md
開き→閉じの対応マップ (open_to_close) とスタックを用いた isValid 実装を追加。入力を単一パスで走査し、開き括弧はスタックにプッシュ、閉じ括弧はスタックトップと照合し不一致や不足で不正と判定。最終的にスタックが空であることを確認するロジック。

Sequence Diagram

sequenceDiagram
    participant User as 入力文字列
    participant Validator as isValid(アルゴリズム)
    participant Stack as スタック
    participant Result as 結果

    User->>Validator: 括弧列を送信
    Note over Validator: 1文字ずつ処理
    alt 文字が開き括弧
        Validator->>Stack: プッシュ(対応する閉じ括弧を期待)
    else 文字が閉じ括弧
        Validator->>Stack: トップを取得
        alt トップが対応する開き括弧
            Stack->>Validator: ポップして続行
        else スタック空または不一致
            Validator->>Result: false を返す
        end
    end
    Note over Validator: 全文字処理完了
    alt スタックが空
        Validator->>Result: true を返す
    else スタック非空
        Validator->>Result: false を返す
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 分

Possibly related PRs

  • Problem/20 grind 2 #5 — 同関数 isValid の実装で括弧マップとスタックベース検証を導入しており、同様の変更点が含まれるため関連性が高い。

Poem

🐰 スタックにぽんと開き乗せて
閉じる声で確認するよ
空になれば合図の鐘
ペアは揃い、行は整う
ひょいと跳ねて、検証完了 🎉

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed PR タイトル「20. Valid Parentheses(251019)」は、変更セットの主な内容を明確に反映しています。ファイル名「20.ValidParentheses_251019.md」と一致し、LeetCode 問題 20 の Valid Parentheses 問題に関する新しいスタックベースの実装を提供するという PR の目的と完全に対応しています。タイトルは具体的で曖昧性がなく、スキャンしている開発者にとって主な変更が何かは明確です。
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch problem/review-20-grind-2-251019

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
20.ValidParentheses_251019.md (1)

34-36: open_to_closeマッピングの選択は適切です

open_to_closeマッピングが推奨される理由:開き括弧を見つけたときにスタックに積み、後で対応する閉じ括弧を検証するというアルゴリズムの流れに自然に合致します。close_to_openの場合、閉じ括弧を見つけたときにスタックトップをルックアップする必要があり、直感的ではなく、逆引きの複雑さが増します。現在のアプローチは標準的で理解しやすいものです。

3~4ヶ月後に独立して異なるアプローチを思いついたことは、問題理解が深まった証です。LeetCodeの模範答案を確認する前に、このアプローチを完成させることは良い学習戦略です。

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 49e01c7 and 9e79e39.

📒 Files selected for processing (1)
  • 20.ValidParentheses_251019.md (1 hunks)
🔇 Additional comments (1)
20.ValidParentheses_251019.md (1)

3-32: 初回の試行が学習プロセスの価値を示している

初回の解答は完成していませんが、括弧マッチングの問題本質を理解し、辞書ベースのアプローチを検討している様子が伝わります。スタック手法への発展につながる有益な思考過程です。

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
20.ValidParentheses_251019.md (1)

95-95: 参考リンクをMarkdownリンク形式で記述してください。

Static analysis hint: MD034 (bare URL detected)

行95の参考リンクを括弧で括り、リンク形式に統一します:

- - https://github.com/h1rosaka/arai60/pull/8/files
+ - [参考: プッシュダウンオートマトン](https://github.com/h1rosaka/arai60/pull/8/files)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9e79e39 and e2152ae.

📒 Files selected for processing (1)
  • 20.ValidParentheses_251019.md (1 hunks)
🧰 Additional context used
🪛 markdownlint-cli2 (0.18.1)
20.ValidParentheses_251019.md

95-95: Bare URL used

(MD034, no-bare-urls)

🔇 Additional comments (2)
20.ValidParentheses_251019.md (2)

74-91: 修正版のスタック実装は正確で適切です。

括弧の優先度を明示する括弧を追加することで、前のバージョンの問題を解決しました(89行目)。アルゴリズムは以下の点で正確です:

  • 開き括弧をスタックに積み、対応する閉じ括弧の期待値を構築
  • s == correct_s で入力文字列と一致確認
  • len(open_brackets_stack) == 0 で未クローズ括弧がないか確認

括弧のネスト、不一致、未クローズのケースをすべて正しく処理します。


60-71: 問題の自己診断と修正の説明が優れています。

Pythonの三項演算子の優先度を正確に分析し、問題を特定し、修正理由を明確に記録しました。このような問題を発見して対応できる能力は重要です。

correct_s = correct_s + char
else:
correct_s = correct_s + open_to_close[open_brackets_stack.pop()] if open_brackets_stack else "#"
return s == correct_s and len(open_brackets_stack) == 0
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

まあ、いいんですが、s == correct_s にならない条件ってなんですかね。
open_to_close[open_brackets_stack.pop()] のあたりでもう分かりませんか。

open_brackets_stack.append(char)
correct_s = correct_s + char
else:
correct_s = correct_s + open_to_close[open_brackets_stack.pop()] if open_brackets_stack else "#"
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if 文と参考演算子が混在しているせいで読みにくく感じました。また、 1 行が長すぎるように感じました。 if 文で書き下したほうが読みやすくなると思います。

correct_s = correct_s + char
else:
correct_s = correct_s + open_to_close[open_brackets_stack.pop()] if open_brackets_stack else "#"
return s == correct_s and len(open_brackets_stack) == 0
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implicit false を利用し、

return s == correct_s and not open_brackets_stack

と書くことをおすすめします。

参考までにスタイルガイドへのリンクを貼ります。

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.

上記のスタイルガイドは唯一絶対のルールではなく、複数あるスタイルガイドの一つに過ぎないということを念頭に置くことをお勧めします。また、所属するチームにより何が良いとされているかは変わります。自分の中で良い書き方の基準を持ちつつ、チームの平均的な書き方で書くことをお勧めいたします。

Comment on lines +85 to +89
if char in open_to_close:
open_brackets_stack.append(char)
correct_s = correct_s + char
else:
correct_s = correct_s + (open_to_close[open_brackets_stack.pop()] if open_brackets_stack else "#" )

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

correct_s = correct_s + char ですが、forループを書き下すと '' + 's[0]' + 's[1]' + ... + 's[-1]' のようなイミュータブルなシーケンスの結合になっており、パフォーマンスの観点から避けるべきだと思います。

イミュータブルなシーケンスの結合は、常に新しいオブジェクトを返します。これは、結合の繰り返しでシーケンスを構築する実行時間コストがシーケンスの長さの合計の二次式になることを意味します。実行時間コストを線形にするには、代わりに以下のいずれかにしてください:

  • str オブジェクトを結合するには、リストを構築して最後に str.join() を使うか、 io.StringIO インスタンスに書き込んで完成してから値を取得してください
    ...

https://docs.python.org/ja/3.13/library/stdtypes.html#string-methods

correct_s = correct_s + char
else:
correct_s = correct_s + (open_to_close[open_brackets_stack.pop()] if open_brackets_stack else "#" )
return s == correct_s and len(open_brackets_stack) == 0

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

correct_sという変数を設けずに実装する方がシンプルに感じます。
具体的にはopen_to_close[open_brackets_stack.pop()]charを比べることで、適切な閉じカッコかを確認します。そうすればループ中に不正な文字が来た時点で処理を打ち切ることができ、最後にはlen(open_brackets_stack) == 0の比較だけで済みます。


(2回目の回答の修正)
```python
class Solution(object):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Python3では、class Solution: で大丈夫です。
もしかすると、leetcodeの設定がpython3になっていないのかもしれません。
pythonとpython3の2つが選べるようになっており紛らわしいのですが、昨今はpython3が主流と思われるので、特別な理由がなければpython3を選んでおいたほうが良さそうです。

@KTakao01
Copy link
Owner Author

KTakao01 commented Oct 25, 2025

レビューありがとうございます。レスが遅くなり申し訳ありません。
体調不良で寝込んでおりますので、来週に対応いたします。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants