classSolution {
publicintscoreOfParentheses(String s) {
return score(s, 0, s.length());
}
privateintscore(String s, int start, int end) {
int balance = 0;
int result = 0;
for (int i = start; i < end; i++) {
if (s.charAt(i) =='(') {
balance++;
} else {
balance--;
}
// When balance equals zero, it means we have a balanced substringif (balance == 0) {
if (i - start == 1) {
// This is a "()" pair result++;
} else {
// This is a (A) structure result += 2 * score(s, start + 1, i);
}
start = i + 1;
}
}
return result;
}
}
classSolution:
defscoreOfParentheses(self, s: str) -> int:
return self.score(s, 0, len(s))
defscore(self, s: str, start: int, end: int) -> int:
balance =0 result =0 i = start
while i < end:
if s[i] =='(':
balance +=1else:
balance -=1# When balance equals zero, it means we have a balanced substringif balance ==0:
if i - start ==1:
# This is a "()" pair result +=1else:
# This is a (A) structure result +=2* self.score(s, start +1, i)
start = i +1 i +=1return result
We can instead use the stack. Let curr records the score at the current layer.
Then, we can go to characters of string, and
When we encounter '(', the current score is pushed to the stack, and curr is reset to 0 as we enter a new inner layer.
When we encounter ')', the curr score is doubled (minimum 1), we exit the current layer, and update curr to the value from the stack plus the curr score.
Similar to the stack approach, we use an array to maintain scores, but instead of pushing and popping elements, we use a pointer to navigate through levels.
classSolution {
publicintscoreOfParentheses(String s) {
int ans = 0, l = 0;
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) =='(') {
l++;
} else {
l--;
if (s.charAt(i - 1) =='(') {
ans += 1 << l; // equivalent to Math.pow(2, l) }
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defscoreOfParentheses(self, s: str) -> int:
ans =0 l =0for i in range(len(s)):
if s[i] =='(':
l +=1else:
l -=1if s[i -1] =='(':
ans +=1<< l # equivalent to 2**lreturn ans