代码
public class Solution {
public bool IsValid(string s) {
if(s==string.Empty) return true;
Stack<char> temp = new Stack<char>();
for (int i = 0; i < s.Length; i++)
{
if(s[i]=='('||s[i]=='['||s[i]=='{')
{
temp.Push(s[i]);
continue;
}
if(temp.Count()==0) return false;
switch (s[i])
{
case ')':
if (temp.Peek() == '(')
temp.Pop();
else return false;
break;
case ']':
if (temp.Peek() == '[')
temp.Pop();
else return false;
break;
case '}':
if (temp.Peek() == '{')
temp.Pop();
else return false;
break;
}
}
if(temp.Count()!=0) return false;
return true;
}
}
思路
for循环检测string中的每一个字符元素
用一个栈储存左括号
当检测到右括号时,检查栈顶元素是否匹配
若是,则弹出栈顶元素并继续循环
若不是或栈为空,则直接返回false
在循环结束后,若栈内还存有元素 说明没有右括号与之匹配,返回false
若以上检测都通过,则返回true