标签:rac lan bool padding [] otto 字符串 bsp title
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.
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;
}
}
标签:rac lan bool padding [] otto 字符串 bsp title
原文地址:http://www.cnblogs.com/xiejunzhao/p/1fdc551bcd9c33a7c024537b9c3fb910.html