
Python3解法:
class Solution:
def isValid(self, s: str) -> bool:
mystack = []
for ss in s:
if (ss=='(' or ss=='{' or ss=='['):
mystack.append(ss)
elif(len(mystack)==0):
return False
else:
if (ss==')'):
if mystack[-1] == '(':
mystack.pop()
else:
return False
elif(ss=='}'):
if mystack[-1] == '{':
mystack.pop()
else:
return False
elif(ss==']'):
if mystack[-1] == '[':
mystack.pop()
else:
return False
else:
return False
if len(mystack)==0:
return True
else:
return False
C++解法:
#include<stack>
class Solution {
public:
bool isValid(string s) {
std::stack<char> mystck;
for(char ss : s){
if(ss=='(' || ss=='[' || ss=='{'){
mystck.push(ss);
}else if(mystck.empty()){
return false;
}else{
if(ss==')' && mystck.top()=='('){
mystck.pop();
}else if(ss=='}' && mystck.top()=='{'){
mystck.pop();
}else if(ss==']' && mystck.top()=='['){
mystck.pop();
}else{
return false;
}
}
}
if(mystck.empty()){
return true;
}else{
return false;
}
}
};
1461

被折叠的 条评论
为什么被折叠?



