LeetCode 20 – Valid Parentheses

Posted on December 25, 2013

Last updated on December 25, 2013

Solution to LeetCode Valid Parentheses problem.

We use a stack to check if the parentheses are valid.

public boolean isValid(String S) {
  Stack<String> s = new Stack<String>();
  for(char c : S.toCharArray()){
    String cc = String.valueOf(c);

    if(c == '{' || c == '(' || c == '[') s.push(cc);

    else{
      if(s.empty()) return false;
      char top = s.peek().toCharArray()[0];

      if( (top == '{' && c == '}') ||
          (top == '(' && c == ')')  ||
          (top == '[' && c == ']') ){
        s.pop();
      } else return false;
    }

  }
  return s.empty();
}
Valid Parentheses
Markdown SHA1: 16fff0a73acf9e788031436c8e50b97b21f6c0fc