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.
public class Solution { /** * @param s A string * @return whether the string is a valid parentheses */ public boolean isValidParentheses(String s) { // Write your code here if(s == null || s.length() == 0) return true; Stack<Character> stack = new Stack<Character>(); int length = s.length(); for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); if(c == '(' || c == '[' || c == '{'){ stack.push(c); } else{ if(c == ')'){ if(stack.isEmpty() || stack.pop() != '(') return false; } else if(c == ']'){ if(stack.isEmpty() || stack.pop() != '[') return false; } else{ if(stack.isEmpty() || stack.pop() != '{') return false; } } } if(stack.isEmpty()) return true; else return false; } }