856. Score of Parentheses
Description
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.
Constraints
Sis a balanced parentheses string, containing only(and).2 <= S.length <= 50
Approach
Links
GeeksforGeeks
ProgramCreek
Examples
Input: "()"
Output: 1
Input: "(())"
Output: 2
Input: "()()"
Output: 2
Input: "(()(()))"
Output: 6
Solutions
/**
* Time complexity : O(N), where N is the length of S.
* Space complexity : O(N), the size of the stack.
*/
class Solution {
public int scoreOfParentheses(String S) {
if(S == null || S.length() == 0) {
return 0;
}
Stack<Integer> stack = new Stack();
int score = 0;
for(char ch: S.toCharArray()) {
if(ch == '(') {
stack.push(score);
score = 0;
} else {
score = stack.pop() + Math.max(score*2, 1);
}
}
return score;
}
}/**
* Time complexity : O(N), where N is the length of S.
* Space complexity : O(1)
*/
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;
}
}Follow up
Last updated
Was this helpful?