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();
}

20 thoughts on “LeetCode – Valid Parentheses (Java)”

  1. Similar solution with less “if-else”-s:


    boolean isValid(String s)
    {
    if (s == null) return true;

    HashMap bracks = new HashMap();
    bracks.put(‘(‘, ‘)’);
    bracks.put(‘[‘, ‘]’);
    bracks.put(‘{‘, ‘}’);

    HashSet closingBrackes = new HashSet(bracks.values());

    Stack stack = new Stack();

    for(int i = 0 ; i < s.length() ; ++i)
    {
    char c = s.charAt(i);

    if (bracks.keySet().contains(c))
    {
    stack.push(c);
    continue;
    }

    if (!(closingBracks.contains(c))) continue

    if (stack.isEmpty()) return false;

    char cOpen = stack.pop();

    if (bracks.get(cOpen) != c) return false;
    }

    return stack.isEmpty();
    }

  2. LeetCode – Valid Parentheses (Java)
    https://ide.geeksforgeeks.org/ZVvldP30eK

    public static boolean Parenthesis(String s){
    if(s.length()%2 != 0) return false;

    Stack stack = new Stack();
    Map mp = new HashMap() {
    {
    put('(',')');
    put('[',']');
    put('{','}');
    }
    };

    for(char ch : s.toCharArray()){
    if(mp.containsKey(ch)){
    stack.push(ch);
    }else if(mp.containsValue(ch)){
    if(stack.isEmpty() || mp.get(stack.pop()) != ch){
    return false;
    }
    }
    }
    return stack.isEmpty();
    }

  3. 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();
    }

  4. 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;
    }

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

  6. 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;
    }

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


  8. 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");
    }

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

  10. 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;
    }
    }

  11. 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;
    }
    }

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

  13. 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;

    }

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

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

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

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

Leave a Comment