标签:
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.
Subscribe to see which companies asked this question
1 public class Solution { 2 public boolean isValid(String s) { 3 if(s == null || s.length() == 0) return false; 4 Stack<Character> stack = new Stack<Character>(); 5 for(int i = 0; i< s.length(); i++){ 6 if(!stack.empty()){ 7 if(s.charAt(i) == ‘)‘ && stack.peek() == ‘(‘) 8 stack.pop(); 9 else if(s.charAt(i) == ‘]‘ && stack.peek() == ‘[‘) 10 stack.pop(); 11 else if(s.charAt(i) == ‘}‘ && stack.peek() == ‘{‘) 12 stack.pop(); 13 else 14 stack.push(s.charAt(i)); 15 }else 16 stack.push(s.charAt(i)); 17 } 18 return stack.empty(); 19 } 20 }
20. Valid Parentheses java solutions
标签:
原文地址:http://www.cnblogs.com/guoguolan/p/5497411.html