Skip to content

Commit 1286cde

Browse files
author
konstantin
committed
Medium856 challenge
1 parent 4e5346d commit 1286cde

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package medium
2+
3+
import StackTopic
4+
import StringTopic
5+
import java.util.*
6+
7+
8+
/**
9+
* 856. Score of Parentheses
10+
* https://leetcode.com/problems/score-of-parentheses/
11+
*
12+
Given a balanced parentheses string s, return the score of the string.
13+
The score of a balanced parentheses string is based on the following rule:
14+
"()" has score 1.
15+
AB has score A + B, where A and B are balanced parentheses strings.
16+
(A) has score 2 * A, where A is a balanced parentheses string.
17+
BULLSHIT
18+
*/
19+
20+
class Medium856 : StringTopic, StackTopic {
21+
22+
fun scoreOfParentheses(s: String): Int {
23+
val stack = Stack<Int>()
24+
stack.push(0)
25+
for (i in s.indices) {
26+
if (s[i] == '(') {
27+
stack.push(0)
28+
} else {
29+
val v = stack.pop()
30+
val w = stack.pop()
31+
stack.push(w + maxOf(2 * v, 1))
32+
}
33+
}
34+
return stack.pop()
35+
}
36+
}
37+
38+
fun main() {
39+
println(Medium856().scoreOfParentheses("()"))
40+
println(Medium856().scoreOfParentheses("(())"))
41+
println(Medium856().scoreOfParentheses("()()"))
42+
println(Medium856().scoreOfParentheses("(()(()))"))
43+
}

0 commit comments

Comments
 (0)