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"(]"And"([)]"Are not.
Solution:
1. If the left parenthesis appears, a matching right parenthesis must be followed.
2. If there is no left parenthesis, there must be no right parenthesis
For 1, open a stack to solve
For example, if there is a right brace, the left brace must already exist (the matching right brace is at the top of the stack)
Open a hashset to judge the right parenthesis.
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 }
Leetcode-valid parentheses