|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 |
| -import java.util.Stack; |
| 3 | +import java.util.ArrayDeque; |
| 4 | +import java.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 | public class _20 {
|
9 | 12 |
|
10 | 13 | public boolean isValid(String s) {
|
11 |
| - Stack<Character> stack = new Stack(); |
12 |
| - char[] schar = s.toCharArray(); |
13 |
| - for(int i = 0; i < schar.length; i++){ |
14 |
| - if(schar[i] == '(' || schar[i] == '[' || schar[i] == '{') stack.push(schar[i]); |
15 |
| - else if(schar[i] == ')' || schar[i] == ']' || schar[i] == '}'){ |
16 |
| - if(stack.isEmpty()) return false; |
| 14 | + Deque<Character> stack = new ArrayDeque<>(); |
| 15 | + for (int i = 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()) return false; |
17 | 20 | else {
|
18 |
| - char pop = stack.pop(); |
19 |
| - if(schar[i] == ')' && pop != '(') return false; |
20 |
| - else if(schar[i] == ']' && pop != '[') return false; |
21 |
| - else if(schar[i] == '}' && pop != '{') return false; |
| 21 | + if (stack.peek() == '(' && s.charAt(i) != ')') return false; |
| 22 | + else if (stack.peek() == '{' && s.charAt(i) != '}') return false; |
| 23 | + else if (stack.peek() == '[' && s.charAt(i) != ']') return false; |
| 24 | + stack.pop(); |
22 | 25 | }
|
23 | 26 | }
|
24 | 27 | }
|
25 | 28 | return stack.isEmpty();
|
26 | 29 | }
|
27 |
| - |
28 | 30 | }
|
0 commit comments