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是否为零
  1. public class Solution {
  2. public bool IsValid(string s) {
  3. Stack<char> stack = new Stack<char>();
  4. foreach(var c in s){
  5. if (stack.Count == 0) {
  6. stack.Push(c);
  7. } else {
  8. if (!IsPair(stack.Peek(), c)) {
  9. stack.Push(c);
  10. } else {
  11. stack.Pop();
  12. }
  13. }
  14. }
  15. return stack.Count == 0;
  16. }
  17. public bool IsPair(char c1,char c2) {
  18. if ((c1 == '(' && c2 == ')') || (c1 == ')' && c2 == '(')) {
  19. return true;
  20. }else if ((c1 == '{' && c2 == '}') || (c1 == '}' && c2 == '{')) {
  21. return true;
  22. }else if ((c1 == '[' && c2 == ']') || (c1 == ']' && c2 == '[')) {
  23. return true;
  24. }
  25. return false;
  26. }
  27. }






posted @ 2017-04-04 11:01  xiejunzhao  阅读(151)  评论(0编辑  收藏  举报