题目链接
https://leetcode.cn/problems/valid-parentheses/
代码实现
java
class Solution {
public boolean isValid(String s) {
if(s.length()%2==1)
{
return false;//若为奇数个,则必不对成
}
Stack<Character> stack=new Stack<Character>();
char sArray[]=s.toCharArray();
for(int i=0;i<sArray.length;i++)
{
char c=sArray[i];
if(c=='(')
{
stack.push('(');
}else if(c=='{')
{
stack.push('{');
}else if(c=='[')
{
stack.push('[');
}else
{
if(stack.isEmpty())return false;//判断是否栈内是否为空,及栈内缺失偶数个字符
char top=stack.peek();
if(c==')'&&top=='(' || c=='}'&&top=='{' || c==']'&&top=='[')
{
stack.pop();
}else
{
return false;
}
}
}
return stack.isEmpty();//判断是否栈内还有其余符号,及栈内多出偶数个字符
}
}
c++
class Solution {
public:
bool isValid(string s) {
if(s.size()%2==1)return false;
stack<char> stack;
for(int i=0;i<s.size();i++)
{
char c=s[i];
if(c=='(')
{
stack.push('(');
}else if(c=='{')
{
stack.push('{');
}else if(c=='[')
{
stack.push('[');
}else
{
if(stack.empty())
{
return false;
}
char top=stack.top();
if(top=='('&&c==')' || top=='{'&&c=='}' ||top=='['&&c==']')
{
stack.pop();
}else
{
return false;
}
}
}
return stack.empty();
}
};
python
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s)%2==1:
return False
stack=list()
for c in s:
if c=='(':
stack.append('(')
elif c=='{':
stack.append('{')
elif c=='[':
stack.append('[')
else:
if not stack:
return False
top=stack[-1]
if (top=='(' and c==')') or (top=='{' and c=='}') or (top=='[' and c==']'):
stack.pop()
else:
return False
return not stack