-
Notifications
You must be signed in to change notification settings - Fork 0
20. Valid Parentheses #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
There was a problem hiding this 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){ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
}()()()()
などの文字列は最後まで見ないでも1文字目を見ただけで有効でないと分かると思います。
There was a problem hiding this comment.
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)){ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
あくまで個人的な感覚なのですが、対応の取れないかっこが現れた時点で return false
してよいように思いました。
There was a problem hiding this comment.
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] == ']'){ |
There was a problem hiding this comment.
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とうことが分かります。
There was a problem hiding this comment.
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){ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
この関数は必要なのでしょうか? isPair
を反転させれば良い気がします。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
isPair
の反転と厳密には等価ではないのと
isPair
の反転だと分かりづらいため、このメソッドがあっても良いかなと思ってます。
https://leetcode.com/problems/valid-parentheses/