LeetCode effective brackets [20]

Title: Given only includes a '(', ')', '{', '}', '[', ']' string, determines 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.

public class LeetCode20 {

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        if("".equals(s))
            return true;
        for(int i =0 ;i<s.length();i++){
            if(stack.empty()){
                stack.push(s.charAt(i));
            }else if(stack.peek().equals('(') && s.charAt(i)==')'
                    || stack.peek().equals('[') && s.charAt(i)==']'
                    || stack.peek().equals('{') && s.charAt(i)=='}'){
                stack.pop();
            }else{
                stack.push(s.charAt(i));
            }
        }
        return stack.empty();
    }
}
Published 55 original articles · won praise 14 · views 20000 +

Guess you like

Origin blog.csdn.net/qq422243639/article/details/103742867