LeetCode--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

注意:1、采用的是栈的方法,栈有五种基本的操作;而,由于stack是泛型,在new时要指定一个character类型;

2、java 的 &&:

(1)例如:(x>y)&&(x>z)
如果x>y的值是false,那么x>z的值将不再计算,(x>y)&&(x>z)直接取值false;
而(x>y)&(x>z);
即使x>y的值是false那么x>z的值仍需计算,尽管x>z的值不会影响x>y&x>z的结果。这就是为什么称&&为“条件与”的理由:只有在满足第一个操作数的值为true的条件下,才计算第二个操作数的值。

(2)运算符优先级:

http://blog.csdn.net/xiaoli_feng/article/details/4567184  

 

public class Solution {

public boolean isValid(String s) {

  if(s.length()%2 !=0) return false;

    Stack<Character> stack = new Stack<Character>();

  for(int i=0, L=s.length(); i<L; i++) {

        char ch = s.charAt(i);

        if(ch==')' || ch==']' || ch=='}') {

            if(stack.isEmpty()) return false;

            if(ch==')' && stack.pop()!='(') return false; //这里要注意: &&前后两个表达式换过来是不成立的

         if(ch==']' && stack.pop()!='[') return false;

        if(ch=='}' && stack.pop()!='{') return false;

        }

      else stack.push(ch);

  }

   return stack.isEmpty() ? true : false;}

}

posted @ 2016-01-04 16:19  wangb021  阅读(159)  评论(0)    收藏  举报