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.

Analysis

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)) {
			stack.push(curr);
		} else if (map.values().contains(curr)) {
			if (!stack.empty() && map.get(stack.peek()) == curr) {
				stack.pop();
			} 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:
<pre><code> 
String foo = "bar";
</code></pre>

  1. tony on 2014-5-3

    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 “{}”

  2. Nacho on 2014-5-5

    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.

  3. Chen Zhang on 2014-6-6

    !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)

  4. gunners86 on 2014-6-8

    nice

  5. Andrei on 2014-6-22

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

  6. Wally Osmond on 2014-12-6

    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.

    Cheers.

    public static boolean validateBrute(String str) {

    int i=0;

    int j=str.length()-1;

    HashMap bMap=new HashMap();

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

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

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

    while(i<j){

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

    return false;

    i++;

    j–;

    }

    return true;

    }

  7. Wally Osmond on 2014-12-6

    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. 🙂

  8. jk on 2015-1-2

    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;
    }else{
    return 0;
    }
    }

  9. Taoufik Bdiri on 2015-4-29

    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));
    stack.push(operator2.charAt(index));
    } 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;
    }
    }

  10. bmm6o on 2015-12-30

    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.)

  11. cc on 2016-2-21

    this solution is very interesting~

  12. Sameer Deswal on 2016-7-27


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

    private static void validate(String str) {
    Stack characters = new Stack();
    for (Character character : str.toCharArray()) {
    if(paranthesis.indexOf(character)>=0){
    if(charMap.keySet().contains(character)){
    if(characters.size()==0){
    System.out.println("Invalid");
    return;
    }else if(!charMap.get(character).equals(characters.peek())){
    System.out.println("Invalid");
    return;
    }else{
    characters.pop();
    }
    }else{
    characters.push(character);
    }

    }
    }
    System.out.println("Valid");
    }

  13. Ryan Biesemeyer on 2016-8-24

    Unfortunately, this solution lets a lot of invalid inputs through: e.g. “[(])”, “((}”, and “[)}”.

  14. Badarinath on 2016-9-5

    simple Solution is to add every character to Hash set and get the size of it. As Set doesn’t store duplicates this is the easiest and simple way to get the count.

    below is the code

    static int longest(String s){
    int result = 0;
    int a = s.length();
    Set set = new HashSet();
    for(int i=0; i<a-1 ; i++){
    set.add(s.charAt(i));
    }
    System.out.println("Length of the string is" + set.size());
    return result;
    }

  15. jesse on 2017-1-11

    This is incorrect. You’re disregarding the order of the parenthesis/brackets. They must be in the proper order, not just counted. Input “)))(((” should return false, your solution would return true.

  16. Danail Kozhuharov on 2017-4-2

    Here is a version with character check time of O(1) (i.e. avoiding the use of a map)

    public static boolean isCorrect(String text) {
    char[] match = new char[256];
    match['('] = '(';
    match[')'] = '(';
    match['['] = '[';
    match[']'] = '[';
    match['{'] = '{';
    match['}'] = '{';

    Stack stack = new Stack();

    for (Character ch1 : text.toCharArray()) {
    char ch2 = match[ch1];
    if (ch2 == ch1) {
    stack.push(ch1);
    } else if (ch2 > 0) {
    if (stack.size() == 0 || ch2 != stack.pop()) {
    return false;
    }
    }
    }
    return stack.size() == 0;
    }

  17. Saeed Aghaee on 2017-7-24

    Instead if a map you could use strings and “indexOf” as follows:

    public static boolean isValid(String str) {
    char[] chars = str.toCharArray();

    String open = “({[“;
    String close = “)}]”;

    Stack stack = new Stack();

    for (int i = 0; i = 0) {
    stack.add(openIndex);
    }
    // close parenthesis
    else if (closeIndex >= 0) {
    int lastOpenIndex = stack.pop();
    if (lastOpenIndex != closeIndex) {
    return false;
    }
    }
    }

    return stack.isEmpty();
    }

Leave a comment

*