AC Java solution


  • 0
    A
    public class Solution {
    public boolean isValid(String s) {
        Stack <Character> stack = new Stack <>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt (i);
            if (stack.empty()) stack.push(c);
            else { 
                char lastC = stack.peek();
                if ( checkLeftRightSimmetry ( lastC, c)) {
                    stack.pop();
                }else{
                    stack.push(c);
                }
            }
        }
        return ( stack.empty() );
    }
    public boolean checkLeftRightSimmetry ( char left, char right ) {
        return ( ( left == '[' && right == ']') ||
                 ( left == '{' && right == '}') ||
                 ( left == '(' && right == ')') );
    }
    

    }


Log in to reply
 

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