File tree 2 files changed +43
-21
lines changed
main/java/com/thealgorithms/strings
test/java/com/thealgorithms/strings
2 files changed +43
-21
lines changed Original file line number Diff line number Diff line change @@ -12,30 +12,49 @@ public static boolean isValid(String s) {
12
12
int head = 0 ;
13
13
for (char c : s .toCharArray ()) {
14
14
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 ] != '[' ) {
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 ] != '[' ) {
32
+ return false ;
33
+ }
34
+ break ;
35
+ default :
36
+ throw new IllegalArgumentException ("Unexpected character: " + c );
37
+ }
38
+ }
39
+ return head == 0 ;
40
+ }
41
+ public static boolean isValidParentheses (String s ) {
42
+ int i = -1 ;
43
+ char [] stack = new char [s .length ()];
44
+ String openBrackets = "({[" ;
45
+ String closeBrackets = ")}]" ;
46
+
47
+ for (char ch : s .toCharArray ()) {
48
+ if (openBrackets .indexOf (ch ) != -1 ) {
49
+ stack [++i ] = ch ;
50
+ } else {
51
+ if (i >= 0 && openBrackets .indexOf (stack [i ]) == closeBrackets .indexOf (ch )) {
52
+ i --;
53
+ } else {
32
54
return false ;
33
55
}
34
- break ;
35
- default :
36
- throw new IllegalArgumentException ("Unexpected character: " + c );
37
56
}
38
57
}
39
- return head == 0 ;
58
+ return i == - 1 ;
40
59
}
41
60
}
Original file line number Diff line number Diff line change @@ -10,15 +10,18 @@ public class ValidParenthesesTest {
10
10
@ Test
11
11
void testOne () {
12
12
assertTrue (ValidParentheses .isValid ("()" ));
13
+ assertTrue (ValidParentheses .isValidParentheses ("()" ));
13
14
}
14
15
15
16
@ Test
16
17
void testTwo () {
17
18
assertTrue (ValidParentheses .isValid ("()[]{}" ));
19
+ assertTrue (ValidParentheses .isValidParentheses ("()[]{}" ));
18
20
}
19
21
20
22
@ Test
21
23
void testThree () {
22
24
assertFalse (ValidParentheses .isValid ("(]" ));
25
+ assertFalse (ValidParentheses .isValidParentheses ("(]" ));
23
26
}
24
27
}
You can’t perform that action at this time.
0 commit comments