Valid Parentheses(左右小括号中括号大括号匹配)leetcode20

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

code:

 public boolean isValid(String s) {
        if(s.equals(""))
            return true;
        if(s==null||s.length()%2==1)
            return false;
        Stack<Character> stack=new Stack<>();
        for(int i=0;i<s.length();i++){
            char sym=s.charAt(i);
            if(sym=='('||sym=='{'||sym=='['){
                stack.add(sym);
                if (stack.size()>= s.length()/2+1)
                    return false;
                //System.out.println(sym);
            }
            else if(sym==')'||sym=='}'||sym==']'){
                char sym2;
                if(stack.isEmpty())
                    return false;
                else
                    sym2=stack.pop();
                if(sym==')'&&sym2=='('||sym==']'&&sym2=='['||sym=='}'&&sym2=='{')
                   continue;
                else
                    return false;
            }
        }
        return stack.isEmpty();
    }

猜你喜欢

转载自blog.csdn.net/m0_37402140/article/details/80473161