Sponsored
Sponsored
This approach leverages a stack to manage the scores of the balanced parentheses string. As we iterate through the string:
At the end of the iteration, the top of the stack will contain the total score.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), due to the stack usage that can store one element per character in the worst case.
1import java.util.Stack;
2
3public class Solution {
4 public static int scoreOfParentheses(String s) {
5 Stack<Integer> stack = new Stack<>();
6 stack.push(0); // Base score
7
8 for (char ch : s.toCharArray()) {
9 if (ch == '(') {
10 stack.push(0);
11 } else {
12 int score = stack.pop();
13 int prevScore = stack.pop();
14 stack.push(prevScore + (score > 0 ? 2 * score : 1));
15 }
16 }
17 return stack.pop();
18 }
19
20 public static void main(String[] args) {
21 String s = "(())";
22 System.out.println("Score: " + scoreOfParentheses(s));
23 }
24}In this Java solution, the stack is used to keep track of the score at each level. When a ')' is encountered, the score at that level is evaluated and then added to the previous level's score. This approach effectively manages nested and sequential parentheses scores.
This approach iteratively computes the score by tracking the depth of parentheses:
Time Complexity: O(n), dictated by the string length.
Space Complexity: O(1), since the depth array size is fixed by constraint.
This Java approach uses an integer array to maintain scores at various depths, ensuring that scores are only accumulated when encountering ')'. Each depth value is adjusted appropriately based on the structure closed.