-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path856-ScoreOfParentheses.go
More file actions
78 lines (68 loc) · 1.87 KB
/
856-ScoreOfParentheses.go
File metadata and controls
78 lines (68 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
// 856. Score of Parentheses
// Given a balanced parentheses string s, return the score of the string.
// The score of a balanced parentheses string is based on the following rule:
// "()" has score 1.
// AB has score A + B, where A and B are balanced parentheses strings.
// (A) has score 2 * A, where A is a balanced parentheses string.
// Example 1:
// Input: s = "()"
// Output: 1
// Example 2:
// Input: s = "(())"
// Output: 2
// Example 3:
// Input: s = "()()"
// Output: 2
// Constraints:
// 2 <= s.length <= 50
// s consists of only '(' and ')'.
// s is a balanced parentheses string.
import "fmt"
// stack
func scoreOfParentheses(s string) int {
stack := make([]int, 0)
stack = append(stack, 0)
max := func (x, y int) int { if x > y { return x; }; return y; }
for _, c := range s {
if c == '(' { // push
stack = append(stack, 0)
continue
}
a, b := stack[len(stack)-1], stack[len(stack)-2]
stack = stack[:len(stack)-2]
stack = append(stack, b + max(2 * a, 1))
}
return stack[0]
}
func scoreOfParentheses1(s string) int {
res, balance := 0, 0
for i := 0; i < len(s); i++ {
if s[i] == '(' {
balance++
continue
}
balance--
if s[i-1] == '(' {
res += 1 << balance
}
}
return res
}
func main() {
// Example 1:
// Input: s = "()"
// Output: 1
fmt.Println(scoreOfParentheses("()")) // 1
// Example 2:
// Input: s = "(())"
// Output: 2
fmt.Println(scoreOfParentheses("(())")) // 2
// Example 3:
// Input: s = "()()"
// Output: 2
fmt.Println(scoreOfParentheses("()()")) // 2
fmt.Println(scoreOfParentheses("()")) // 1 1
fmt.Println(scoreOfParentheses("(())")) // 2 1 * 2
fmt.Println(scoreOfParentheses("()()")) // 2 1 + 1
}