Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
class Solution {
public:
bool match(char a, char b) {
if (a == '[' && b == ']') return true;
if (a == '(' && b == ')') return true;
if (a == '{' && b == '}') return true;
return false;
}
bool isValid(string s) {
int len = s.size();
if (len % 2 == 1) return false;
stack<char> r;
int i = 0;
r.push(s[i++]);
while (i < len) {
if (r.empty()) {
r.push(s[i++]);
continue;
}
if (match(r.top(), s[i])) {
r.pop(); i++;
} else {
r.push(s[i++]);
}
}
if (r.empty()) return true;
else return false;
}
};

本文介绍了一种使用栈数据结构来验证包含括号的字符串是否有效的算法。该算法通过检查括号是否正确配对和闭合,判断字符串的有效性。例如,'()' 和 '()[]{}
843

被折叠的 条评论
为什么被折叠?



