前言
Valid Parentheses是Leetcode的一道基础题,考察括号匹配算法,使用栈结构。
题目
题目描述
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.
题目分析
括号匹配的思路比较简单,检测输入字符串中的字符,若是左括号就入栈,若是右括号,就pop一个元素表示与其配对,配对成功则继续访问下一个字符,否则退出。出现非括号字符则跳过。
代码
class Solution {
public:
bool isValid(string s) {
string left = "([{";
string right = ")]}";
stack<char> stk;
for (int i = 0; i < s.size(); i++) {
if (left.find(s[i]) != string::npos) {
stk.push(s[i]);
} else {
if (stk.empty() || stk.top() != left[right.find(s[i])])
return false;
else
stk.pop();
}
}
return stk.empty();
}
};
在这里说明几点:
- string类型的find()函数将返回字符(即find的参数)在该串中的位置索引,若未找到(即无该字符)返回string::npos
- 主循环中的i还可用自动指针(auto pointer)实现,如下:
for (auto atp : s) {
if (left.find(atp) != string::npos) {
stk.push(atp);
} else {
if (stk.empty() || stk.top() != left[right.find(atp)])
return false;
else
stk.pop();
}
}