Java solution with stack, easy to read


  • 0
    L
    public class ValidParentheses_20 {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (stack.isEmpty()) {
                stack.push(ch);
            } else {
                char top = stack.peek();
                if (isMatch(top, ch)) {
                    stack.pop();
                } else {
                    stack.push(ch);
                }
            }
        }
    
        return stack.isEmpty();
    }
    
    private boolean isMatch(char ch1, char ch2) {
        return (ch1 == '(' && ch2 == ')') || (ch1 == '[' && ch2 == ']') ||
                (ch1 == '{' && ch2 == '}');
    
    }
    
    public static void main(String[] args) {
        ValidParentheses_20 validParentheses = new ValidParentheses_20();
        System.out.println(validParentheses.isValid("()"));
        System.out.println(validParentheses.isValid("()[]{}"));
        System.out.println(validParentheses.isValid("([)]"));
        System.out.println(validParentheses.isValid("([)]"));
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.