856. Score of Parentheses
/**
* Problem: LeetCode 856 - Score of Parentheses
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int scoreOfParentheses(String s) {
int score = 0;
int depth = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
depth++;
} else {
depth--;
// Direct "()" pair found
if (s.charAt(i - 1) == '(') {
score += 1 << depth;
}
}
}
return score;
}
}
"""
Problem: LeetCode 856 - Score of Parentheses
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
class Solution:
def scoreOfParentheses(self, s: str) -> int:
score = 0
depth = 0
for i in range(len(s)):
if s[i] == '(':
depth += 1
else:
depth -= 1
# Direct "()" pair found
if s[i - 1] == '(':
score += 1 << depth
return score
/**
* Problem: LeetCode 856 - Score of Parentheses
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <string>
using namespace std;
/**
* Problem: LeetCode 856 - Score of Parentheses
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
int scoreOfParentheses(string s) {
int score = 0;
int depth = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '(') {
depth++;
} else {
depth--;
// Direct "()" pair found
if (s[i - 1] == '(') {
score += 1 << depth;
}
}
}
return score;
}
};
/**
* Problem: LeetCode 856 - Score of Parentheses
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
var scoreOfParentheses = function(s) {
let score = 0;
let depth = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === '(') {
depth++;
} else {
depth--;
// Direct "()" pair found
if (s[i - 1] === '(') {
score += 1 << depth;
}
}
}
return score;
};
TIME COMPLEXITY
O(N) where N = s.length