题目
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
示例 1:
输入:s = "()"
输出:true
思路
当出现右括号时,如'(','{','[‘ 必定需要对象的左括号,才能时是个闭合的字符串
代码
public bool IsValid(string s)
{
List<char> ayyayC = new List<char>();
foreach (char c in s)
{
if (c == '(' || c == '{' || c == '[')
{
ayyayC.Add(c);
}
else
{
if(ayyayC.Count == 0) return false;
if (leftParentheses(ayyayC[ayyayC.Count - 1]) == rightParentheses(c))
{
ayyayC.RemoveAt(ayyayC.Count - 1);
}
else
{
return false;
}
}
}
if (ayyayC.Count == 0) return true;
return false;
} public int leftParentheses(char c)
{
switch (c)
{
case '(':
return 1;
case '{'
:
return 2;
case '[':
return 3;
default:
return 0;
}
} public int rightParentheses(char c)
{
switch (c)
{
case ')':
return 1;
case '}'
:
return 2;
case ']':
return 3;
default:
return 0;
}
}