1. 题目
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.
2. 思路
如果是有效的,则符合有序的先进后出序列,构造栈进行模拟验证。
顺序扫描,遇到左括号进栈,遇到右括号弹栈进行匹配,不匹配则失败。匹配则继续。
扫描完之后,如果占里还有数据,或者弹栈匹配时无数据可弹,都是失败。
3. 代码
class Solution {
public:
Solution() {
for (int i = 0; i < 128; i++) {
wh[i] = 0;
re[i] = false;
}
wh['('] = wh[')'] = 1;
wh['['] = wh[']'] = 2;
wh['{'] = wh['}'] = 3;
re[')'] = re[']'] = re['}'] = true;
}
bool isValid(string s) {
int len = s.length();
if (len == 0) return true;
vector<char> stack;
for (int i = 0; i < len; i++) {
char ch = s[i];
if (re[ch]) {
if (stack.empty()) return false;
char last = stack.back();
if (wh[last] != wh[ch]) {
return false;
} else {
stack.pop_back();
}
} else {
stack.push_back(ch);
}
}
if (stack.empty()) return true;
else return false;
}
private:
int wh[128];
bool re[128];
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。