class Solution{
public:
bool isValid(string s){
stack<char> mystack;
char now;
char instack;
int n = s.length();for(int i=n;i>0;i--){
now = s[i-1];if(!mystack.empty()){//如果栈非空
instack = mystack.top();//读取一个元素}else{
instack = NULL;//else 是对应这个用例 "[[[]"}if( now =='('&& instack ==')'){mystack.pop();}elseif( now =='{'&& instack =='}'){mystack.pop();}elseif( now =='['&& instack ==']'){mystack.pop();}else{mystack.push(now);}}return mystack.empty();}};
其他解法
classSolution:
def isValid(self, s):while'{}' in s or'()' in s or'[]' in s:
s = s.replace('{}','')
s = s.replace('[]','')
s = s.replace('()','')return s ==''
classSolution{public boolean isValid(String s){int length = s.length()/2;for(int i =0; i < length; i++){
s = s.replace("()","").replace("{}","").replace("[]","");}return s.length()==0;}}