首页 > 其他 > 详细

20. 括号的合法性 Valid Parentheses

时间:2017-04-04 11:44:24      阅读:176      评论:0      收藏:0      [点我收藏+]

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. }






20. 括号的合法性 Valid Parentheses

原文:http://www.cnblogs.com/xiejunzhao/p/1fdc551bcd9c33a7c024537b9c3fb910.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!