Valid Parentheses
2015-04-01 10:15 笨笨的老兔子 阅读(147) 评论(0) 编辑 收藏 举报有一个由各种括号组成的字符串,判断其是否合法
合法准则即是否成对匹配
(())合法
({])不合法
())(不合法
思路:用栈模拟即可
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
for (size_t i = 0; i < s.size(); i++)
{
if (stk.empty())
stk.push(s[i]);
else if (isPair(stk.top(),s[i]))
{
stk.pop();
}
else
{
stk.push(s[i]);
}
}
return stk.empty() ? true : false;
}
bool isPair(char left, char right)
{
if (left == '(' && right == ')')
return true;
if (left == '[' && right == ']')
return true;
if (left == '{' && right == '}')
return true;
return false;
}
};