|
1 | 1 | packagecom.fishercoder.solutions;
|
2 | 2 |
|
3 |
| -importjava.util.Stack; |
| 3 | +importjava.util.ArrayDeque; |
| 4 | +importjava.util.Deque; |
4 | 5 |
|
5 |
| -/**Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. |
6 |
| -
|
7 |
| - The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.*/ |
| 6 | +/** |
| 7 | + * 20. Valid Parentheses |
| 8 | + * |
| 9 | + * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. |
| 10 | + * The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.*/ |
8 | 11 | publicclass_20 {
|
9 | 12 |
|
10 | 13 | publicbooleanisValid(Strings) {
|
11 |
| -Stack<Character>stack =newStack(); |
12 |
| -char[]schar =s.toCharArray(); |
13 |
| -for(inti =0;i <schar.length;i++){ |
14 |
| -if(schar[i] =='(' ||schar[i] =='[' ||schar[i] =='{')stack.push(schar[i]); |
15 |
| -elseif(schar[i] ==')' ||schar[i] ==']' ||schar[i] =='}'){ |
16 |
| -if(stack.isEmpty())returnfalse; |
| 14 | +Deque<Character>stack =newArrayDeque<>(); |
| 15 | +for (inti =0;i <s.length();i++) { |
| 16 | +if (s.charAt(i) =='(' ||s.charAt(i) =='{' ||s.charAt(i) =='['){ |
| 17 | +stack.push(s.charAt(i)); |
| 18 | +}else { |
| 19 | +if(stack.isEmpty())returnfalse; |
17 | 20 | else {
|
18 |
| -charpop =stack.pop(); |
19 |
| -if(schar[i] ==')' &&pop !='(')returnfalse; |
20 |
| -elseif(schar[i] ==']' &&pop !='[')returnfalse; |
21 |
| -elseif(schar[i] =='}' &&pop !='{')returnfalse; |
| 21 | +if (stack.peek() =='(' &&s.charAt(i) !=')')returnfalse; |
| 22 | +elseif (stack.peek() =='{' &&s.charAt(i) !='}')returnfalse; |
| 23 | +elseif (stack.peek() =='[' &&s.charAt(i) !=']')returnfalse; |
| 24 | +stack.pop(); |
22 | 25 | }
|
23 | 26 | }
|
24 | 27 | }
|
25 | 28 | returnstack.isEmpty();
|
26 | 29 | }
|
27 |
| - |
28 | 30 | }
|