20. Valid Parentheses

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

The general idea is: given a bracket string, judge whether it is legal or not

I have no idea, and then I read the code of the big guy in the discussion, it's really amazing,

Idea: Every time you see a left parenthesis, push a matching right parenthesis into the stack. If it is not a left parenthesis, there are two possibilities:

    Situation 1: The right parenthesis comes. If it is legal, it must be the same as the symbol at the top of the stack; there are actually two situations in the stack:

                Stack situation 1: The stack is empty -- "Illegal

                Stack situation 2: The stack is not empty, then it is necessary to judge the characters on the top of the stack and the characters that come. Consistent -- "legal, inconsistent --" illegal

    Case 2: What comes is empty,

                 Stack situation 1: the stack is empty, -- "legal;

                Stack situation 2: The stack is empty, ——" is illegal

Knowledge points:

1.

publicchar[] toCharArray() 
Convert String to char array of characters

2. for loop, iterating over the array

for(char c:str.toCharArray()){}

3. If it is not empty and the character on the top of the stack is equal to the incoming character, it should be: just pop the top of the stack, and then continue to make subsequent judgments without returning a value

Therefore, this operation can be done in the judgment statement without entering the judgment condition.

code

class Solution {
    public boolean isValid(String s) {
        Stack stack = new Stack<Character>();
        for( Character c:s.toCharArray()){//This is very important. It was previously defined as char type, but because stack.pop is of object type, the result is consistent in the judgment condition. The type does not conform to the error.
            if(c=='(')
                stack.push(')');
            else if(c=='[')
                stack.push(']');
            else if(c=='{')
                stack.push('}');
            else if(stack.isEmpty()){
                return false;
            }else if(!stack.isEmpty()){
                if(stack.pop()!=c){
                    return false;
                }
            }
        }
        return stack.isEmpty();
        
    }
   
}









Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325688448&siteId=291194637