856. Score of Parentheses LeetCode Solution
In this guide, you will get 856. Score of Parentheses LeetCode Solution with the best time and space complexity. The solution to Score of Parentheses problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Score of Parentheses solution in C++
- Score of Parentheses solution in Java
- Score of Parentheses solution in Python
- Additional Resources
Problem Statement of Score of Parentheses
Given a balanced parentheses string s, return the score of the string.
The score of a balanced parentheses string is based on the following rule:
“()” has score 1.
AB has score A + B, where A and B are balanced parentheses strings.
(A) has score 2 * A, where A is a balanced parentheses string.
Example 1:
Input: s = “()”
Output: 1
Example 2:
Input: s = “(())”
Output: 2
Example 3:
Input: s = “()()”
Output: 2
Constraints:
2 <= s.length <= 50
s consists of only '(' and ')'.
s is a balanced parentheses string.
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
856. Score of Parentheses LeetCode Solution in C++
class Solution {
public:
int scoreOfParentheses(string s) {
int ans = 0;
int layer = 0;
for (int i = 0; i + 1 < s.length(); ++i) {
const char a = s[i];
const char b = s[i + 1];
if (a == '(' && b == ')')
ans += 1 << layer;
layer += a == '(' ? 1 : -1;
}
return ans;
}
};
/* code provided by PROGIEZ */
856. Score of Parentheses LeetCode Solution in Java
class Solution {
public int scoreOfParentheses(String s) {
int ans = 0;
int layer = 0;
for (int i = 0; i + 1 < s.length(); ++i) {
final char a = s.charAt(i);
final char b = s.charAt(i + 1);
if (a == '(' && b == ')')
ans += 1 << layer;
layer += a == '(' ? 1 : -1;
}
return ans;
}
}
// code provided by PROGIEZ
856. Score of Parentheses LeetCode Solution in Python
class Solution:
def scoreOfParentheses(self, s: str) -> int:
ans = 0
layer = 0
for a, b in itertools.pairwise(s):
if a + b == '()':
ans += 1 << layer
layer += 1 if a == '(' else -1
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.