Conversation
| */ | ||
| bool isValid(string s) { | ||
| int index = 0; | ||
| while (index < s.length()) { |
There was a problem hiding this comment.
"()(" こういう入力で コケる 間違えると思います。1回のparseParensは左括弧から対応する右括弧までしかparseしないので。
...とコメントを考えて、上のBNFと合っておらず関数名が悪い気がしました。parseSingleParensとか...?
There was a problem hiding this comment.
あー、すみません。理解しました。parseParens は、1つ目の対応するカッコまでしか consume しないからですね。そうですね。parseParens の中にそれを入れたほうが素直な気がしますがどうでしょうか。
There was a problem hiding this comment.
たしかにそう思います。こんな感じですかね
class Solution {
public:
/*
parens := singleParen*
singleParen := '(' singleParens ')' | '{' singleParens '}' | '[' singleParens ']'
*/
bool isValid(string s) {
int index = 0;
return parseParens(s, index);
}
private:
static bool parseParens(const string& s, int& index) {
while (index < s.length()) {
if (!parseSingleParen(s, index)) return false;
}
return true;
}
static bool parseSingleParen(const string& s, int& index) {
if (index >= s.length()) return false;
const char left_paren = consume(s, index);
if (!isLeftParen(left_paren) || index >= s.length()) return false;
while (!matchPairParen(left_paren, s[index])) {
if (!parseSingleParen(s, index)) return false;
}
consume(s, index); // right paren
return true;
}
static char consume(const string& s, int& index) {
return s[index++];
}
static bool matchPairParen(const char left, const char right) {
return left == '(' && right == ')' || left == '{' && right == '}' || left == '[' && right == ']';
}
static bool isLeftParen(const char ch) {
return ch == '(' || ch == '{' || ch == '[';
}
};There was a problem hiding this comment.
いや、 singleParenは singleParen := '(' singleParen ')' | '{' singleParen '}' | '[' singleParen ']' | '' こうか。上のBNFだと無限ループしますね (微妙にtypoもしている)
There was a problem hiding this comment.
singleParen := '(' parens ')' | '{' parens '}' | '[' parens ']'ではないですか?
parseSingleParenのロジックがちょっと複雑な気がしますね。
There was a problem hiding this comment.
singleParen := '(' parens ')' | '{' parens '}' | '[' parens ']'ではないですか?
おっしゃる通りでした。自分の書いたのだと (()()) こういうのが通らないですね
| public: | ||
| ParenParser() : index(0) {} | ||
|
|
||
| bool parse(const string& input) { |
There was a problem hiding this comment.
2回同じstringを入れると、indexが動いてしまっているため、正しく動かないのではないでしょうか?
| return parens(input) && index == input.length(); | ||
| } | ||
|
|
||
| bool parens(const string& input) { |
https://leetcode.com/problems/valid-parentheses/description/