File tree 2 files changed +21
-0
lines changed
main/java/com/thealgorithms/strings
test/java/com/thealgorithms/strings
2 files changed +21
-0
lines changed Original file line number Diff line number Diff line change @@ -38,4 +38,22 @@ public static boolean isValid(String s) {
38
38
}
39
39
return head == 0 ;
40
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
+ for (char ch : s .toCharArray ()) {
47
+ if (openBrackets .indexOf (ch ) != -1 ) {
48
+ stack [++i ] = ch ;
49
+ } else {
50
+ if (i >= 0 && openBrackets .indexOf (stack [i ]) == closeBrackets .indexOf (ch )) {
51
+ i --;
52
+ } else {
53
+ return false ;
54
+ }
55
+ }
56
+ }
57
+ return i == -1 ;
58
+ }
41
59
}
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