leetcode--Valid Parentheses
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.
1 public class Solution { 2 public boolean isValid(String s) { 3 boolean isValid = true; 4 if(s.length() > 0){ 5 Stack<Character> parenStack = new Stack<Character>(); 6 for(int i = 0; i <s.length(); ++i){ 7 if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') 8 parenStack.push(s.charAt(i)); 9 else{ 10 if(s.charAt(i) == ')'){ 11 if(parenStack.empty() || parenStack.peek() != '(') 12 isValid = false; 13 else 14 parenStack.pop(); 15 } 16 if(s.charAt(i) == ']'){ 17 if(parenStack.empty() || parenStack.peek() != '[') 18 isValid = false; 19 else 20 parenStack.pop(); 21 } 22 if(s.charAt(i) == '}'){ 23 if(parenStack.empty() || parenStack.peek() != '{') 24 isValid = false; 25 else 26 parenStack.pop(); 27 } 28 } 29 } 30 if(! parenStack.empty()) 31 isValid = false; 32 } 33 return isValid; 34 } 35 }