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. use i to scan every characer of string
  2. when it comes to left parentheses, we push it into Stack. Otherwise, it comes to right parentheses. We pop left one from Stack , checking whether they are valid brackets.
  3. we use try, catch because

代码

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();       
        for(int i = 0; i< s.length(); i++){
            char c = s.charAt(i);
            if(c == '(' ||c == '{' ||c == '[' ){
                stack.push(c);
            }else{
                try {
                char top = stack.pop();
                if (!(( c == ')' &&  top =='(' )
                    ||(c == '}' && top =='{' )
                    ||(c == ']' && top =='[' ))){
                    return false;
                }
            }catch (Exception e){return false;}         
            }
        }
        return stack.isEmpty();      
    }
}

results matching ""

    No results matching ""