Given a balanced parentheses string
S, compute the score of the string based on the following rule:()has score 1ABhas scoreA + B, where A and B are balanced parentheses strings.(A)has score2 * A, where A is a balanced parentheses string.
Example 1:
Input: "()" Output: 1
Example 2:
Input: "(())" Output: 2
Example 3:
Input: "()()" Output: 2
Example 4:
Input: "(()(()))" Output: 6
Note:
Sis a balanced parentheses string, containing only(and).2 <= S.length <= 50
class Solution {
public int scoreOfParentheses(String S) {
if (S == null || S.length() == 0) {
return 0;
}
int ans = 0;
Stack<Integer> stack = new Stack<>();
for (char c : S.toCharArray()) {
if (c == '(') {
stack.push(-1);
} else {
int curr = 0;
while (stack.peek() != -1) {
curr += stack.pop();
}
stack.pop(); // '('
if (curr == 0) {
curr = 1;
} else {
curr *= 2;
}
stack.push(curr);
}
}
while (!stack.isEmpty()) {
ans += stack.pop();
}
return ans;
}
}
Solution 2: O(1) spaceWe use a counter to maintain the number of open left parenthesis.
If the current char is '(', counter++
If the current is ')', counter--
If the current is "()" we know the current number of open left parentheiss outside,
then score += 1 << counter
The key observation for the solution is score of (()()()) = (()) + (()) + (()), so we can calculate
the score and sum it up.
Code (Java):
class Solution {
public int scoreOfParentheses(String S) {
int left = 0;
int score = 0;
for (int i = 0; i < S.length(); i++) {
char c = S.charAt(i);
if (c == '(') {
left++;
} else {
left--;
if (S.charAt(i - 1) == '(') {
score += 1 << left;
}
}
}
return score;
}
}
No comments:
Post a Comment