Short solution in java


  • 4
    J
    import java.util.Stack;
    
    public class Solution {
        public boolean isValid(String s) {
            Stack<Character> stack = new Stack<Character>();
    
            for (int i = 0; i < s.length(); i++){
                char c = s.charAt(i);
                if (stack.isEmpty() && (c == '}' || c == ']' || c == ')')) return false;
                else
                    if (!stack.isEmpty() && isMatched(stack.peek(), c)) stack.pop();
                    else
                        stack.push(c);
            }
            if (stack.isEmpty()) return true;
            else return false;
        }
        
        public boolean isMatched(char a, char b){
            if (a == '(' && b == ')') return true;
            if (a == '[' && b == ']') return true;
            if (a == '{' && b == '}') return true;
            return false;
        }
    }

  • 0
    This post is deleted!

Log in to reply
 

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