Java solution without []{}(), just use ASCII


  • 0
    W

    From ASCII, we could find ( is 40, ) is 41, [ is 91, ] is 93, { is 123 and } is 125. Also, since the string just contains parentheses, we could come up with the following code.

    public class Solution {
        public boolean isValid(String s) {
            if (s == null || s.length() == 0) {
                return false;
            }
            
            Stack<Character> stack = new Stack<Character>();
            for (char c : s.toCharArray()) {
                if (stack.isEmpty()) {
                    stack.push(c);
                } else if (c == stack.peek() + 1 || c == stack.peek() + 2) {
                    stack.pop();
                } else {
                    stack.push(c);
                }
            }
            return stack.isEmpty();
        }
    }
    

Log in to reply
 

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