856. Score of Parentheses
Description
Given a balanced parentheses string S
, compute the score of the string based on the following rule:
()
has score 1AB
has scoreA + B
, where A and B are balanced parentheses strings.(A)
has score2 * A
, where A is a balanced parentheses string.
Constraints
S
is a balanced parentheses string, containing only(
and)
.2 <= S.length <= 50
Approach
Links
GeeksforGeeks
ProgramCreek
Examples
Input: "()"
Output: 1
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;
}
}
Follow up
Last updated
Was this helpful?