LeetCode – Valid Parentheses (Java)

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.


A typical problem which can be solved by using a stack data structure.

Java Solution

public static boolean isValid(String s) {
	HashMap<Character, Character> map = new HashMap<Character, Character>();
	map.put('(', ')');
	map.put('[', ']');
	map.put('{', '}');
	Stack<Character> stack = new Stack<Character>();
	for (int i = 0; i < s.length(); i++) {
		char curr = s.charAt(i);
		if (map.keySet().contains(curr)) {
		} else if (map.values().contains(curr)) {
			if (!stack.empty() && map.get(stack.peek()) == curr) {
			} else {
				return false;
	return stack.empty();
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • Sameer Deswal

    static Map charMap = new HashMap();
    charMap.put(']', '[');
    charMap.put('}', '{');
    charMap.put(')', '(');;
    static String paranthesis="{}[]()";
    public static void main(String[] args) {
    String str="{}[]()";
    String str1="{][][}";
    String str2="{[()]}";

    private static void validate(String str) {
    Stack characters = new Stack();
    for (Character character : str.toCharArray()) {
    }else if(!charMap.get(character).equals(characters.peek())){


  • cc

    this solution is very interesting~

  • bmm6o

    It’s true that map.values.contains() has complexity linear with the size of the map. It’s incorrect to simply combine that with the O(n) of the loop (linear in the length of the input). (Also note that the map has constant size.)

  • Here is my solution accepted by LeetCode using a Stack, and 2 strings.

    public class Solution {
    public boolean isValid(String s) {
    Stack stack = new Stack();
    String operator = “({[“;
    String operator2 = “)}]”;
    for (int i = 0; i < s.length(); i++) {
    if (operator.contains(s.substring(i, i + 1))) {
    int index = operator.indexOf(s.substring(i, i + 1));
    } else if (stack.isEmpty())
    return false;
    else {
    char myChar = stack.pop();
    if (myChar != s.charAt(i))
    return false;
    if (!stack.empty())
    return false;
    return true;

  • jk

    public boolean validEquation(String s){
    if(s == null){
    throw new IllegalArgumentException(“String parameter is null” );
    boolean result = false;
    int sum = 0;
    char[] arr = s.toCharArray();
    for (char c : arr){
    sum += getCharVal(c);
    if(sum < 0){
    return result;
    return result = (sum == 0 ? true:false);

    private int getCharVal(char c) {
    if(c =='('){
    return 1;
    }else if(c ==')'){
    return -1;
    }else if(c =='{'){
    return 2;
    }else if(c =='}'){
    return -2;
    }else if(c =='['){
    return 3;
    }else if(c ==']'){
    return -3;
    return 0;

  • Wally Osmond

    Ah, my solution only works for the first string given. Should have read it more clearly. But I still don’t like the original as it doesn’t handle nested brackets of duplicated types. I know the question isn’t demanding it however that’s only because the question is easier than it should be. 🙂

  • Wally Osmond

    You don’t get to show off that you know how to use a stack this way, which I’m sure for many is the point, but I believe it’s a more efficient and straight forward solution to just use a while loop since. Half the iterations. No stack overhead.


    public static boolean validateBrute(String str) {

    int i=0;

    int j=str.length()-1;

    HashMap bMap=new HashMap();


    bMap.put(‘[‘, ‘]’);

    bMap.put(‘{‘, ‘}’);


    if(bMap.get(str.charAt(i)) != str.charAt(j))

    return false;




    return true;


  • Andrei

    Good solution, but just in case. map.values().contains() has linear complexity unlike map.keys.contains() so overall solution has quadratic complexity.

  • gunners86


  • Chen Zhang

    !stack.isEmpty() should be added in the else if sentence rather than its if sentence:
    else if (!stack.isEmpty() && map.values().contains(curr)) {
    if (map.get(stack.peek()) == curr)

  • Nacho

    The problem doesn’t requires any relative order between the parenthesis, brackets and square brackets. The only order it requires is the closing order, meaning you must previously have an open parenthesis in order to close it, so the sequence “([{}])” that you mention is completely valid.

  • tony

    your code didn’t check the order of the parenthesis. how about the input is “([{}])”. The “()” should be inside of “[]”, and “[]” should be inside of “{}”