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.
solution:
1.如果左括号出现了,后面必须出现一个匹配的右括号
2.如果没有左括号,那么必定不能有右括号
针对1,开个栈解决
针对2,反过来想,如果有右括号,势必要有左括号已经出现过了(与其匹配的右括号在栈顶)
为了判断右括号,开个Hashset吧
1 public boolean isValid(String s) { 2 if(s== null || s.length() ==0){ 3 return true; 4 } 5 Stack<Byte> brackets = new Stack<Byte>(); 6 HashSet<Byte> sets = new HashSet<Byte>(); 7 sets.add((byte) ')'); 8 sets.add((byte) ']'); 9 sets.add((byte) '}'); 10 byte [] sBytes = s.getBytes(); 11 for(int i =0;i<sBytes.length;i++){ 12 if(sBytes[i] == '('){ 13 brackets.push((byte) ')'); 14 continue; 15 } 16 if(sBytes[i] == '{'){ 17 brackets.push((byte) '}'); 18 continue; 19 } 20 if(sBytes[i] == '['){ 21 brackets.push((byte) ']'); 22 continue; 23 } 24 if(sets.contains(sBytes[i])){ 25 if(!brackets.isEmpty() && brackets.peek() == sBytes[i]){ 26 brackets.pop(); 27 }else{ 28 return false; 29 } 30 } 31 } 32 return brackets.isEmpty(); 33 }