Leetcode (Java) -20. Effective brackets

Includes only a given '(', ')' string, '{', '}', '[', ']', and determine whether the string is valid.

Valid string must meet:

Left bracket must be closed by a closing parenthesis of the same type.
Left parenthesis must be closed in the correct order.
Note the empty string can be considered a valid string.

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

Ideas:

Use the stack, the input string traversal

If the current character to the left half of the brackets, it is pushed onto the stack

If you come across the right half of the brackets, Category talk:

1) If the stack is not empty and the left half of the corresponding bracket, the top element is removed, continue to cycle

2) If the stack is empty at this time, the process directly returns false

3) If the left half of the corresponding bracket, false otherwise

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();

        int length=s.length();
        for(int i=0;i<length;i++)
        {
            char ch=s.charAt(i);
            if(ch=='(' || ch=='[' || ch=='{')
                stack.push(s.charAt(i));
            else{
                if(stack.isEmpty()){
                    return false;
                }
                char topChar=stack.pop();
                if(ch==')' && topChar!='(')
                    return false;
                else if(ch==']' && topChar!='[')
                    return false;
                else if(ch=='}' && topChar!='{')
                    return false;
            }
        }
        return stack.isEmpty();
    }
}

 

Published 142 original articles · won praise 31 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_38905818/article/details/104065023