#################################################
堆栈方法即可解决
python中可用列表代替堆栈使用
#################################################
class Solution:
def isValid(self, s: str) -> bool:
stack = []
use = {"[":"]","{":"}","(":")"}
for i in range(len(s)):
if s[i] == "[" or s[i]== "(" or s[i]=="{":
stack.append(s[i])
elif s[i] == "]" or s[i] == ")" or s[i]=="}":
if stack != []:
if s[i] == use[stack.pop()]:
continue
else:
return False
else:
return False
if stack == []:
return True
else:
return False
class Solution {
public:
bool isValid(string s) {
stack<char> stac;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '(' || s[i] == '{' || s[i] == '[')
{
stac.push(s[i]);
}
else
{
if (stac.empty()) {
return false;
}
else {
if (s[i] == ']' )
{
if (stac.top() == '[')
{
stac.pop();
continue;
}
else
{
return false;
}
}
if (s[i] == '}')
{
if (stac.top() == '{')
{
stac.pop();
continue;
}
else
{
return false;
}
}
if (s[i] == ')')
{
if (stac.top() == '(')
{
stac.pop();
continue;
}
else
{
return false;
}
}
}
}
}
if (stac.empty())
{
return true;
}
else
{
return false;
}
}
};