https://leetcode-cn.com/problems/valid-parentheses/
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。
示例1:
输入:"()"
输出:true
示例2:
输入:"()[]{}"
输出:true
示例3:
输入:"(]"
输出:false
示例4:
输入:"([)]"
输出:false
示例5:
输入:"{[]}"
输出:true
虽然是简单题,但是水了4次才过 用栈
class Solution {
public:
bool isValid(string s) {
int len = s.length();
if( len==0 ) return true;
if( len % 2 ) return false;
stack<char> temp;
for(int i=0; i<len; i++){
if( s[i]=='(' || s[i]=='{' || s[i]=='[' ){
temp.push(s[i]);
}
else if( temp.size()==0 ){
return false;
}
else if( s[i]==')' && temp.top()!='(' ){
return false;
}
else if( s[i]=='}' && temp.top()!='{' ){
return false;
}
else if( s[i]==']' && temp.top()!='[' ){
return false;
}
else{
temp.pop();
}
}
if( temp.size()==0 ) return true;
else return false;
}
};