Skip to content

20. Valid Parentheses#4

Merged
colorbox merged 2 commits intomainfrom
20
Mar 12, 2024
Merged

20. Valid Parentheses#4
colorbox merged 2 commits intomainfrom
20

Conversation

@colorbox
Copy link
Copy Markdown
Owner

Copy link
Copy Markdown

@hayashi-ay hayashi-ay left a comment

Choose a reason for hiding this comment

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

チョムスキー階層、type-2、文脈自由文法、プッシュダウンオートマトンですね。

bool isValid(string s) {
stack<char> stack;

for(char c: s){
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

}()()()()などの文字列は最後まで見ないでも1文字目を見ただけで有効でないと分かると思います。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

確かに、最初の一文字を調べるだけで早期returnが可能ですね


for(char c : s){
// stack topとのチェック
if(!stack.empty() && isPair(stack.top(), c)){
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

あくまで個人的な感覚なのですが、対応の取れないかっこが現れた時点で return false してよいように思いました。

Copy link
Copy Markdown
Owner Author

@colorbox colorbox Mar 12, 2024

Choose a reason for hiding this comment

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

なるほど、c{,(,[などであれば、ペアにしようがないので、メソッド呼び出しが不要ですね

勘違いしました(}みたいなのが出てきた時点でreturn false可能ということですね。

bool isValid(string s) {
stack<char> stack;

if(s[0] == ')' || s[0] == '}' || s[0] == ']'){
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

for文の中で考慮できると思うんですよね。
以前の指摘と似ていますが、[]([][][][]の場合は3文字目を見たタイミングで早期リターンできます。

要はclose bracketsが登場した際に、stackが空であればこのタイミングでFalseとうことが分かります。

Copy link
Copy Markdown
Owner Author

@colorbox colorbox Mar 13, 2024

Choose a reason for hiding this comment

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

あー、なるほど、ありがとうございます、その発想はなかったです。
確かにclose bracketとstackの状況を参照するだけでfalseにできますね・・・

return (l == '(' && r == ')' || l == '{' && r == '}' || l == '[' && r == ']');
}

bool isInvalidPair(char l, char r){
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

この関数は必要なのでしょうか? isPairを反転させれば良い気がします。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

isPairの反転と厳密には等価ではないのと
isPairの反転だと分かりづらいため、このメソッドがあっても良いかなと思ってます。

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.

3 participants