|
1 | 1 | package com.thealgorithms.strings;
|
2 | 2 | // Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine
|
| 3 | + |
3 | 4 | // if the input string is valid. An input string is valid if: Open brackets must be closed by
|
4 | 5 | // the same type of brackets. Open brackets must be closed in the correct order. Every close
|
5 | 6 | // bracket has a corresponding open bracket of the same type.
|
6 | 7 |
|
7 | 8 | public final class ValidParentheses {
|
8 | 9 | private ValidParentheses() {
|
9 | 10 | }
|
| 11 | + |
10 | 12 | public static boolean isValid(String s) {
|
11 | 13 | char[] stack = new char[s.length()];
|
12 | 14 | int head = 0;
|
13 | 15 | for (char c : s.toCharArray()) {
|
14 | 16 | switch (c) {
|
15 |
| - case '{': |
16 |
| - case '[': |
17 |
| - case '(': |
18 |
| - stack[head++] = c; |
19 |
| - break; |
20 |
| - case '}': |
21 |
| - if (head == 0 || stack[--head] != '{') { |
22 |
| - return false; |
23 |
| - } |
24 |
| - break; |
25 |
| - case ')': |
26 |
| - if (head == 0 || stack[--head] != '(') { |
27 |
| - return false; |
28 |
| - } |
29 |
| - break; |
30 |
| - case ']': |
31 |
| - if (head == 0 || stack[--head] != '[') { |
| 17 | + case '{': |
| 18 | + case '[': |
| 19 | + case '(': |
| 20 | + stack[head++] = c; |
| 21 | + break; |
| 22 | + case '}': |
| 23 | + if (head == 0 || stack[--head] != '{') { |
| 24 | + return false; |
| 25 | + } |
| 26 | + break; |
| 27 | + case ')': |
| 28 | + if (head == 0 || stack[--head] != '(') { |
| 29 | + return false; |
| 30 | + } |
| 31 | + break; |
| 32 | + case ']': |
| 33 | + if (head == 0 || stack[--head] != '[') { |
| 34 | + return false; |
| 35 | + } |
| 36 | + break; |
| 37 | + default: |
| 38 | + throw new IllegalArgumentException("Unexpected character: " + c); |
| 39 | + } |
| 40 | + } |
| 41 | + return head == 0; |
| 42 | + } |
| 43 | + |
| 44 | + public static boolean isValidParentheses(String s) { |
| 45 | + int i = -1; |
| 46 | + char[] stack = new char[s.length()]; |
| 47 | + String openBrackets = "({["; |
| 48 | + String closeBrackets = ")}]"; |
| 49 | + |
| 50 | + for (char ch : s.toCharArray()) { |
| 51 | + if (openBrackets.indexOf(ch) != -1) { |
| 52 | + stack[++i] = ch; |
| 53 | + } else { |
| 54 | + if (i >= 0 && openBrackets.indexOf(stack[i]) == closeBrackets.indexOf(ch)) { |
| 55 | + i--; |
| 56 | + } else { |
32 | 57 | return false;
|
33 | 58 | }
|
34 |
| - break; |
35 |
| - default: |
36 |
| - throw new IllegalArgumentException("Unexpected character: " + c); |
37 | 59 | }
|
38 | 60 | }
|
39 |
| - return head == 0; |
| 61 | + return i == -1; |
40 | 62 | }
|
41 | 63 | }
|
0 commit comments