给定一个字符串所表示的括号序列,包含以下字符: '(', ')'
, '{'
, '}'
, '['
和 ']'
, 判定是否是有效的括号序列。
样例
括号必须依照 "()"
顺序表示, "()[]{}"
是有效的括号,但 "([)]"
则是无效的括号。
挑战
O(n)的时间,n为括号的个数
其中栈的基本操作有:
1、入栈 push()
2、出栈 pop()
3、访问栈顶 top()
4、判断栈空 empty()
5、栈中元素数量 size()
class Solution {
public:
/**
* @param s A string
* @return whether the string is a valid parentheses
*/
bool isValidParentheses(string& s) {
// Write your code here
stack<char> stack_char;
int length = s.length();
for(int i=0;i<length;++i){
if(s[i]=='(' || s[i]=='[' || s[i]=='{'){
stack_char.push(s[i]);
}
if(!stack_char.empty()){
if(s[i]==')'){
if(stack_char.top()=='('){
stack_char.pop();
}
else{
return false;
}
}
if(s[i]==']'){
if(stack_char.top()=='['){
stack_char.pop();
}
else{
return false;
}
}
if(s[i]=='}'){
if(stack_char.top()=='{'){
stack_char.pop();
}
else{
return false;
}
}
}
else{
return false;
}
}
return stack_char.empty();
}
};