描述:
给定一个字符串所表示的括号序列,包含以下字符: '(', ')'
, '{'
, '}'
, '['
and ']'
, 判定是否是有效的括号序列。
样例
括号必须依照 "()"
顺序表示, "()[]{}"
是有效的括号,但 "([)]"
则是无效的括号。
解题思路:使用栈
class Solution {
public:
/**
* @param s A string
* @return whether the string is a valid parentheses
*/
bool isMatch(char a, char b)
{
if(a == '(' && b == ')')
return true;
if(a == '[' && b == ']')
return true;
if(a == '{' && b == '}')
return true;
return false;
}
bool isValidParentheses(string& s) {
// Write your code here
int n = s.length();
if(n < 1) return true;
if(n % 2) return false;
stack<char> paren;
paren.push(s[0]);
int i = 1;
while(i < n)
{
if(!paren.empty() && isMatch(paren.top(),s[i]))
paren.pop();
else
paren.push(s[i]);
i++;
}
if(!paren.empty()) return false;
else return true;
}
};