Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’
and ‘]’, determine if the input string is valid.The brackets must close in the correct order, “()” and “()[]{}” are
all valid but “(]” and “([)]” are not.
经典题,对于([{入栈,)]}出栈,如果出栈时无法与当前括号成对直接return false,如果出栈时栈为空return false,如果扫描完字符串栈中还有元素return false。
C# Code
public class Solution
{
public bool IsValid(string s)
{
Stack<char> stack = new Stack<char>();
if (s.Length == 1 || s.Length % 2 == 1) return false;
foreach (char temp in s)
{
if (temp == '(' || temp == '{' || temp == '[')
{
stack.Push(temp);
}
try
{
if (temp == ')' || temp == '}' || temp == ']')
{
char pre = stack.Pop();
if (pre == '(' && temp != ')')
{
return false;
}
if (pre == '[' && temp != ']')
{
return false;
}
if (pre == '{' && temp != '}')
{
return false;
}
}
}
catch
{
return false;
}
}
if (stack.Count == 0)
return true;
else return false;
}
}