Java String brackets validation

It’s a very popular task to validate opening/closing brackets (as well as parentheses) in a text or string.


The proposed algorithm implementations are based on java.util.Stack and java.util.Map.

Single-method implementation

public static boolean isBracketsValid(String text) {
    Map<Character, Character> openCloseMap = new HashMap<>();
    openCloseMap.put('(', ')');
    openCloseMap.put('[', ']');
    openCloseMap.put('{', '}');

    Stack<Character> stack = new Stack<>();
    for (char ch : text.toCharArray()) {
        if (openCloseMap.containsKey(ch)) {
            stack.push(ch);
        } else if (openCloseMap.containsValue(ch)) {
            if (stack.isEmpty() || !openCloseMap.get(stack.pop()).equals(ch)) {
                return false;
            }
        }
    }
    return stack.isEmpty();
}

Usage:

System.out.println(isBracketsValid("()"));
System.out.println(isBracketsValid("(())"));
System.out.println(isBracketsValid("()[]{}"));
System.out.println(isBracketsValid("([{}])"));

System.out.println(isBracketsValid(")"));
System.out.println(isBracketsValid("(("));
System.out.println(isBracketsValid("(]"));
System.out.println(isBracketsValid("({)"));

Output:

true
true
true
true
false
false
false
false

Separate-class implementation

This implementation is developed to make opening/closing brackets customizable via a constructor with a simple set of chars (String).

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * @author Denis Migol
 */
public class BracketsValidator {
    private static final String DEFAULT_BRACKETS = "()[]{}";

    private final Map<Character, Character> openCloseMap;

    public BracketsValidator() {
        this(DEFAULT_BRACKETS);
    }

    public BracketsValidator(String brackets) {
        this.openCloseMap = extractBrackets(brackets);
    }

    public BracketsValidator(Map<Character, Character> openCloseMap) {
        this.openCloseMap = openCloseMap;
    }

    private Map<Character, Character> extractBrackets(String brackets) {
        int halfLength = brackets.length() / 2;
        Map<Character, Character> openCloseMap = new HashMap<>(halfLength);
        for (int i = 0; i < halfLength; i++) {
            openCloseMap.put(brackets.charAt(2 * i), brackets.charAt(2 * i + 1));
        }
        return Collections.unmodifiableMap(openCloseMap);
    }

    public boolean isBracketsValid(String text) {
        Stack<Character> stack = new Stack<>();
        for (char ch : text.toCharArray()) {
            if (openCloseMap.containsKey(ch)) {
                stack.push(ch);
            } else if (openCloseMap.containsValue(ch)) {
                if (stack.isEmpty() || !openCloseMap.get(stack.pop()).equals(ch)) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}

Usage:

BracketsValidator validator = new BracketsValidator("()[]{}<>");

System.out.println(validator.isBracketsValid("(hello)"));
System.out.println(validator.isBracketsValid("(some [text])"));
System.out.println(validator.isBracketsValid("([<{}>])"));
System.out.println(validator.isBracketsValid("([{}])(<>)[({<>})]"));

System.out.println(validator.isBracketsValid(")"));
System.out.println(validator.isBracketsValid("(])"));
System.out.println(validator.isBracketsValid("([<{}>]"));
System.out.println(validator.isBracketsValid("()(]"));

Output:

true
true
true
true
false
false
false
false