Monday, May 15, 2017

Valid Parentheses


Problem Statement

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.

Link to GitHub :Code


Solution

  • Move all the string into charArray
  • Iterate through the charArray. While iterating push the opposite characters to a stack
  • In the next iteration compare the closing parentheses with the one in the stack.If it does not match then return false
  • Return true if it passes through the iteration with matching parentheses
public static boolean get(String s)
 {
  Stack<Character>  stack= new Stack<Character>();
  //Iterate through the string
  for(char c: s.toCharArray())
  {
   if(c =='(')
   {
    stack.push(')');
   }
   else if(c=='{')
   {
    stack.push('}');
   }
   else if(c=='[')
   {
    stack.push(']');
   }
   else if(stack.isEmpty() || stack.pop()!=c)
   {
    return false;
   }
  }
  //It would return true if the stack is empty or it would return false
  return stack.isEmpty();

No comments:

Post a Comment