File tree 2 files changed +22
-0
lines changed
main/java/com/thealgorithms/strings
test/java/com/thealgorithms/strings
2 files changed +22
-0
lines changed Original file line number Diff line number Diff line change @@ -38,4 +38,23 @@ 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
+
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 {
54
+ return false ;
55
+ }
56
+ }
57
+ }
58
+ return i == -1 ;
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