Skip to content

Commit 284cb07

Browse files
committed
add Kotlin solution for 678. Valid Parenthesis String
1 parent 3024189 commit 284cb07

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
class Solution {
2+
3+
fun checkValidString(s: String): Boolean {
4+
// number of opening parenthesis when '*' is taken as '('
5+
var noOfOpenParenthesisWhenStarIsAnOpeningParenthesis = 0
6+
// number of opening parenthesis when '*' is taken as ')'
7+
var noOfOpenParenthesisWhenStarIsAClosingParenthesis = 0
8+
// number of opening parenthesis when '*' is taken as ' '
9+
var noOfOpenParenthesisWhenStarIsAnEmptyString = 0
10+
11+
for (char in s) {
12+
if (char == '(') {
13+
noOfOpenParenthesisWhenStarIsAnOpeningParenthesis++
14+
noOfOpenParenthesisWhenStarIsAClosingParenthesis++
15+
noOfOpenParenthesisWhenStarIsAnEmptyString++
16+
17+
}
18+
if (char == '*') {
19+
noOfOpenParenthesisWhenStarIsAnOpeningParenthesis++
20+
noOfOpenParenthesisWhenStarIsAClosingParenthesis--
21+
}
22+
23+
if (char == ')') {
24+
noOfOpenParenthesisWhenStarIsAnOpeningParenthesis--
25+
noOfOpenParenthesisWhenStarIsAClosingParenthesis--
26+
noOfOpenParenthesisWhenStarIsAnEmptyString--
27+
}
28+
// A negative value indicates an excess of closing parenthesis.
29+
// Eg: -1 indicates that there are no opening parenthesis and 1 closing parenthesis.
30+
// If at least one of our possibilities is a positive value, then it indicates
31+
// that the string is possibly valid.
32+
// If all of our possibilities have a negative value, it indicates that none of the
33+
// possibilities lead to a valid string. Hence, return false.
34+
if (
35+
noOfOpenParenthesisWhenStarIsAnOpeningParenthesis < 0 &&
36+
noOfOpenParenthesisWhenStarIsAClosingParenthesis < 0 &&
37+
noOfOpenParenthesisWhenStarIsAnEmptyString < 0
38+
) return false
39+
40+
// Ensure that the variables are always positive. A negative value doesn't make sense
41+
// because there cannot be a negative number of opening parenthesis.
42+
noOfOpenParenthesisWhenStarIsAnOpeningParenthesis =
43+
noOfOpenParenthesisWhenStarIsAnOpeningParenthesis.coerceAtLeast(0)
44+
45+
noOfOpenParenthesisWhenStarIsAClosingParenthesis =
46+
noOfOpenParenthesisWhenStarIsAClosingParenthesis.coerceAtLeast(0)
47+
48+
noOfOpenParenthesisWhenStarIsAnEmptyString =
49+
noOfOpenParenthesisWhenStarIsAnEmptyString.coerceAtLeast(0)
50+
51+
}
52+
53+
return noOfOpenParenthesisWhenStarIsAnOpeningParenthesis == 0 ||
54+
noOfOpenParenthesisWhenStarIsAClosingParenthesis == 0 ||
55+
noOfOpenParenthesisWhenStarIsAnEmptyString == 0
56+
}
57+
}

0 commit comments

Comments
 (0)