public class Solution {
Stack<char> S = new Stack<char>(); public bool IsValid(string s)
{
foreach (var c in s)
{
if (c == '(' || c == '[' || c == '{')
{
S.Push(c);
}
else if(c == ')')
{
if (S.Count > )
{
var k = S.Peek();
if (k == '(')
{
S.Pop();
}
else
{
return false;
}
}
else
{
return false;
}
}
else if (c == ']')
{
if (S.Count > )
{
var k = S.Peek();
if (k == '[')
{
S.Pop();
}
else
{
return false;
}
}
else
{
return false;
}
}
else if (c == '}')
{
if (S.Count > )
{
var k = S.Peek();
if (k == '{')
{
S.Pop();
}
else
{
return false;
}
}
else
{
return false;
}
}
}
if (S.Count > )
{
return false;
}
else
{
return true;
}
}
}

https://leetcode.com/problems/valid-parentheses/#/description

补充一个python的实现:

 class Solution:
def isValid(self, s: str) -> bool:
n = len(s)
if n == :
return True
stack = []
for c in s:
if c == '(' or c == '{' or c == '[':
stack.append(c)
elif c == ')':
if len(stack) > :
if stack[-] == '(':
stack.pop(-)
else:
stack.append(')')
else:
return False
elif c == '}':
if len(stack) > :
if stack[-] == '{':
stack.pop(-)
else:
stack.append('}')
else:
return False
elif c == ']':
if len(stack) > :
if stack[-] == '[':
stack.pop(-)
else:
stack.append(']')
else:
return False
if len(stack) == :
return True
else:
return False
05-07 15:43