-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathScoreOfParentheses.java
94 lines (78 loc) · 2.21 KB
/
ScoreOfParentheses.java
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
class Solution {
public int scoreOfParentheses(String s) {
int ans = 0, bal = 0;
for (int i = 0; i < S.length(); ++i) {
if (S.charAt(i) == '(') {
bal++;
} else {
bal--;
if (S.charAt(i-1) == '(')
ans += 1 << bal;
}
}
return ans;
}
public int scoreOfParentheses(String s) {
Stack<Integer> st = new Stack<>();
for(int i=0; i<s.length(); i++) {
char ch = s.charAt(i);
if(ch == '(') {
// Treat -1 as '('
st.push(-1);
} else {
if(st.peek() == -1) {
st.pop();
st.push(1);
} else {
int score = 0;
while(st.peek() != -1) score += st.pop();
st.pop();
st.push(2*score);
}
}
}
int ans = 0;
while(!st.isEmpty()) ans += st.pop();
return ans;
}
}
// M-III
// Using Tree
class Solution {
class Node {
Node parent = null;
ArrayList<Node> child = new ArrayList<>();
public void setParent(Node parent) {
this.parent = parent;
}
public Node getParent() {
return parent;
}
public int getScore() {
if(child.size() == 0) {
return 1;
}
int ans = 0;
for(Node node: child) {
ans += node.getScore();
}
if(parent == null) return ans;
else return 2*ans;
}
}
public int scoreOfParentheses(String s) {
Node cur = new Node();
Node root = cur;
for(int i=0; i<s.length(); i++) {
if(s.charAt(i) == '(') {
Node temp = new Node();
cur.child.add(temp);
temp.setParent(cur);
cur = temp;
} else {
cur = cur.getParent();
}
}
return root.getScore();
}
}