Valid Parentheses

medium Strings

Problem

Read one line made only of the characters ( ) [ ] { }. Print true if every opening bracket is closed by the same kind of bracket in the correct order, else false.

Constraints

  • 1 <= length <= 10^5

Examples

Input

([]){}

Output

true

Input

(]

Output

false

Solutions

Best approachTime O(n)Space O(n)

The last opened bracket must be closed first (last in, first out). That is exactly what a stack does.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process one line of text.
 * Input   : One line of text.
 * Output  : true or false.
 * Approach: Use a stack.
 * Time    : O(n)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static boolean solve(String s) {
        // Step 1: A stack keeps the opening brackets that are still waiting for a partner.
        java.util.ArrayDeque<Character> stack = new java.util.ArrayDeque<>();

        for (char c : s.toCharArray()) {
            // Step 2: An opening bracket goes on the stack.
            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            } else {
                // Step 3: A closing bracket needs an opening bracket on top of the stack.
                if (stack.isEmpty()) {
                    return false;
                }
                char open = stack.pop();

                // Step 4: The pair must have the same kind.
                if ((c == ')' && open != '(') || (c == ']' && open != '[') || (c == '}' && open != '{')) {
                    return false;
                }
            }
        }

        // Step 5: At the end nothing may be left waiting.
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.hasNextLine() ? scanner.nextLine() : "";
        System.out.println(solve(s));
    }
}
Hints (1)
  1. Which bracket must be closed first?