Very easy to understand solution in Java


  • 0
    R
    public static boolean checkParenthesis(String str) {
            if (str.isEmpty())
                return true;
    
            Stack<Character> stack = new Stack<Character>();
            for (int i = 0; i < str.length(); i++) {
                char current = str.charAt(i);
                if (current == '{' || current == '(' || current == '[')
                    stack.push(current);
    
                if (current == '}' || current == ')' || current == ']') {
                    if (stack.isEmpty())
                        return false;
                    char last = stack.peek();
                    if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[')
                        stack.pop();
                    else 
                        return false;
                }
            }
            return stack.isEmpty();
        }
    }

Log in to reply
 

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