Leetcode Valid Parentheses problem solution in Java programming

In the Leetcode Valid Parentheses problem solution in Java programming Given a string s containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.

Leetcode Valid Parentheses problem solution in Java programming

import java.util.*;

class Solution {
  Stack<Character> stack = new Stack<Character>();
  Map<Character, Character> map = new HashMap<Character, Character>();

  public Solution() {
    map.put('[', ']');
    map.put('{', '}');
    map.put('(', ')');
  }

  public boolean isValid(String s) {
    if (s.length() < 2) {
      return false;
    }
    for (int i = 0; i < s.length(); i++) {
      Character currentChar = s.charAt(i);
      if (map.get(currentChar) != null) {
        stack.push(map.get(currentChar));
      } else if (stack.size() == 0) {
        return false;
      } else if (currentChar == stack.peek()) {
        stack.pop();
      } else {
        return false;
      }
    }

    if (stack.size() > 0) {
      return false;
    }

    return true;
  }
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *