Conversation
hayashi-ay
left a comment
There was a problem hiding this comment.
チョムスキー階層、type-2、文脈自由文法、プッシュダウンオートマトンですね。
| bool isValid(string s) { | ||
| stack<char> stack; | ||
|
|
||
| for(char c: s){ |
There was a problem hiding this comment.
}()()()()などの文字列は最後まで見ないでも1文字目を見ただけで有効でないと分かると思います。
There was a problem hiding this comment.
確かに、最初の一文字を調べるだけで早期returnが可能ですね
|
|
||
| for(char c : s){ | ||
| // stack topとのチェック | ||
| if(!stack.empty() && isPair(stack.top(), c)){ |
There was a problem hiding this comment.
あくまで個人的な感覚なのですが、対応の取れないかっこが現れた時点で return false してよいように思いました。
There was a problem hiding this comment.
なるほど、cが{,(,[などであれば、ペアにしようがないので、メソッド呼び出しが不要ですね
勘違いしました(}みたいなのが出てきた時点でreturn false可能ということですね。
| bool isValid(string s) { | ||
| stack<char> stack; | ||
|
|
||
| if(s[0] == ')' || s[0] == '}' || s[0] == ']'){ |
There was a problem hiding this comment.
for文の中で考慮できると思うんですよね。
以前の指摘と似ていますが、[]([][][][]の場合は3文字目を見たタイミングで早期リターンできます。
要はclose bracketsが登場した際に、stackが空であればこのタイミングでFalseとうことが分かります。
There was a problem hiding this comment.
あー、なるほど、ありがとうございます、その発想はなかったです。
確かにclose bracketとstackの状況を参照するだけでfalseにできますね・・・
| return (l == '(' && r == ')' || l == '{' && r == '}' || l == '[' && r == ']'); | ||
| } | ||
|
|
||
| bool isInvalidPair(char l, char r){ |
There was a problem hiding this comment.
この関数は必要なのでしょうか? isPairを反転させれば良い気がします。
There was a problem hiding this comment.
isPairの反転と厳密には等価ではないのと
isPairの反転だと分かりづらいため、このメソッドがあっても良いかなと思ってます。
https://leetcode.com/problems/valid-parentheses/