20. 括号的合法性 Valid Parentheses
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.
题意:判断字符串中的括号组合是否合法
解法:使用用栈,如果新字符与栈顶字符成对执行POP,不成对执行PUSH。最后判断Count是否为零
public class Solution {
public bool IsValid(string s) {
Stack<char> stack = new Stack<char>();
foreach(var c in s){
if (stack.Count == 0) {
stack.Push(c);
} else {
if (!IsPair(stack.Peek(), c)) {
stack.Push(c);
} else {
stack.Pop();
}
}
}
return stack.Count == 0;
}
public bool IsPair(char c1,char c2) {
if ((c1 == '(' && c2 == ')') || (c1 == ')' && c2 == '(')) {
return true;
}else if ((c1 == '{' && c2 == '}') || (c1 == '}' && c2 == '{')) {
return true;
}else if ((c1 == '[' && c2 == ']') || (c1 == ']' && c2 == '[')) {
return true;
}
return false;
}
}