码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Valid Parentheses

时间:2015-09-22 13:03:44      阅读:138      评论: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.


解题思路:

经典老题,用stack。

一个个检查给的characters,如果是左括号都入栈;如果是右括号,检查栈如果为空,证明不能匹配,如果栈不空,弹出top,与当前扫描的括号检查是否匹配。

全部字符都检查完了以后,判断栈是否为空,空则正确都匹配,不空则证明有没匹配的。

注意:检查char是用==


 Java code:

public boolean isValid(String s) {
          if(s.length() == 0) {
              return false;
          }
          Stack<Character> x = new Stack<Character>();
          for(int i = 0; i < s.length(); i++) {
              if(s.charAt(i) ==‘(‘ || s.charAt(i) == ‘[‘ || s.charAt(i) == ‘{‘) {
                  x.push(s.charAt(i));
              }else{
                  if(x.size() == 0){
                      return false;
                  }
                  char y = s.charAt(i);
                  char z = x.pop();
                  if(!((y == ‘)‘ && z == ‘(‘) || (y == ‘]‘ && z == ‘[‘) 
                      || (y == ‘}‘ && z == ‘{‘))){
                          return false;
                  }
              }
          }
          return x.size() == 0;
    }

Reference:

1. http://www.cnblogs.com/springfor/p/3869420.html

 

Leetcode Valid Parentheses

标签:

原文地址:http://www.cnblogs.com/anne-vista/p/4828548.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!