20. Valid Parentheses

来源:互联网 发布:java手机游戏免费下载 编辑:程序博客网 时间:2024/06/03 17:40

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 boolean isValid(String s) {

   if(s==null||s.length()==1)

   return false;

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

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

       if(s.charAt(i)=='('||s.charAt(i)=='{'||s.charAt(i)=='['){

       stack.push(s.charAt(i));

       }else{

       if(stack.empty()){

       return false;

       }else{

       char c = s.charAt(i);

if((c==')'&&stack.pop()=='(')||(c==']'&&stack.pop()=='[')||(c=='}'&&stack.pop()=='{')){

       continue;

       }else{

       return false;

       }

       }        

       }

       }

       return stack.isEmpty();

   }


0 0