https://leetcode.com/problems/score-of-parentheses/
Approach 2: Stack
https://www.acwing.com/solution/LeetCode/content/825/
定义一个记录分数的栈,初始时放入 0 当做答案。
如果遇到左括号,则 0 入栈。
如果遇到右括号,则弹出栈顶;如果栈顶元素为 t = 0,则说明右括号是和上一个左括号相邻的,故此时的栈顶加 1;否则此时的栈顶加 2 * t。
最后栈中一定还剩一个元素,这个元素就是答案。
X.
Solution1: Recursion
Time complexity: O(n^2)
https://zxi.mytechroad.com/blog/string/leetcode-856-score-of-parentheses/
X. Build binary tree
https://medium.com/@poitevinpm/solution-to-leetcode-problem-856-score-of-parentheses-90dba4fd6f7b
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.
Example 1:
Input: "()" Output: 1
Example 2:
Input: "(())" Output: 2
Example 3:
Input: "()()" Output: 2
Example 4:
Input: "(()(()))" Output: 6
Note:
S
is a balanced parentheses string, containing only(
and)
.2 <= S.length <= 50
https://www.acwing.com/solution/LeetCode/content/825/
定义一个记录分数的栈,初始时放入 0 当做答案。
如果遇到左括号,则 0 入栈。
如果遇到右括号,则弹出栈顶;如果栈顶元素为 t = 0,则说明右括号是和上一个左括号相邻的,故此时的栈顶加 1;否则此时的栈顶加 2 * t。
最后栈中一定还剩一个元素,这个元素就是答案。
int scoreOfParentheses(string S) {
stack<int> score;
score.push(0);
for (auto &c : S) {
if (c == '(')
score.push(0);
else {
int t = score.top();
score.pop();
if (t == 0)
score.top() += 1;
else
score.top() += 2 * t;
}
}
return score.top();
}
public int scoreOfParentheses(String S) {
Stack<Integer> stack = new Stack<>();
stack.push(0); // The score of the current frame
for (char c : S.toCharArray()) {
if (c == '(')
stack.push(0);
else {
int top = stack.pop();
int result = stack.pop();
if (top == 0)
result += 1;
else
result += 2 * top;
stack.push(result);
}
}
return stack.pop();
}
Every position in the string has a depth - some number of matching parentheses surrounding it. For example, the dot in
(()(.()))
has depth 2, because of these parentheses: (__(.__))
Our goal is to maintain the score at the current depth we are on. When we see an opening bracket, we increase our depth, and our score at the new depth is 0. When we see a closing bracket, we add twice the score of the previous deeper part - except when counting
()
, which has a score of 1.
For example, when counting
(()(()))
, our stack will look like this:[0, 0]
after parsing(
[0, 0, 0]
after(
[0, 1]
after)
[0, 1, 0]
after(
[0, 1, 0, 0]
after(
[0, 1, 1]
after)
[0, 3]
after)
[6]
after)
public int scoreOfParentheses(String S) {
Stack<Integer> stack = new Stack();
stack.push(0); // The score of the current frame
for (char c : S.toCharArray()) {
if (c == '(')
stack.push(0);
else {
int v = stack.pop();
int w = stack.pop();
stack.push(w + Math.max(2 * v, 1));
}
}
return stack.pop();
}
public int scoreOfParentheses(String S) {
Stack<Integer> stack = new Stack<>();
for (char c : S.toCharArray()) {
if (c == '(') {
stack.push(-1);
} else {
int cur = 0;
while (stack.peek() != -1) {
cur += stack.pop();
}
stack.pop();
stack.push(cur == 0 ? 1 : cur * 2);
}
}
int sum = 0;
while (!stack.isEmpty()) {
sum += stack.pop();
}
return sum;
}
I used array here because it seems to be easier to write.
N
is quite small and we don't need to push/pop repeatedly.O(N)
time and O(N)
space public int scoreOfParentheses(String S) {
int res[] = new int[30], i = 0;
for (char c : S.toCharArray())
if (c == '(') res[++i] = 0;
else res[i - 1] += Math.max(res[i--] * 2, 1);
return res[0];
}
Approach 2: Count layers and add score when meet "()"
public int scoreOfParentheses(String S) {
int res = 0, layers = 0;
for (int i = 0; i < S.length(); ++i) {
if (S.charAt(i) == '(') layers++; else layers--;
if (S.charAt(i) == '(' && S.charAt(i + 1) == ')') res += 1 << (layers - 1);
}
return res;
}
X. Approach 3: Count Cores
http://reeestart.me/2018/12/23/LeetCode-856-Score-of-Parentheses/
http://reeestart.me/2018/12/23/LeetCode-856-Score-of-Parentheses/
为什么给这道题TAG了一个MATH, 是因为仔细观察一下, 比如((((())))) = 2 2 2 * 2 = 2^4
所以只要维护一个层数即可得到答案. 碰到开括号层数加一, 反之层数减一. 只有当开闭括号连续出现的时候, 将2^deep 加入到res中即可.
The final sum will be a sum of powers of 2, as every core (a substring
()
, with score 1) will have it's score multiplied by 2 for each exterior set of parentheses that contains that core.
Algorithm
Keep track of the
balance
of the string, as defined in Approach #1. For every )
that immediately follows a (
, the answer is 1 << balance
, as balance
is the number of exterior set of parentheses that contains this core.
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;
}
https://blog.csdn.net/qq2667126427/article/details/80793443
int scoreOfParentheses(string S) {
int cnt = 0;
int res = 0;
// 记录上一个字符
char last = ' ';
for (auto &ch : S) {
// 深度加大
if (ch == '(') {
cnt++;
}
else {
// 深度变小
cnt--;
// 上一个是'('表名这一对是(),可以加分
if (last == '(') {
res += 1 << cnt;
}
}
// 记录字符
last = ch;
}
return res;
}
int scoreOfParentheses(string S) {
int cnt = 0;
int res = 0;
// 记录上一个字符
char last = ' ';
for (auto &ch : S) {
// 深度加大
if (ch == '(') {
cnt++;
}
else {
// 深度变小
cnt--;
// 上一个是'('表名这一对是(),可以加分
if (last == '(') {
res += 1 << cnt;
}
}
// 记录字符
last = ch;
}
return res;
}
Approach 1: Divide and Conquer
Split the string into
S = A + B
where A
and B
are balanced parentheses strings, and A
is the smallest possible non-empty prefix of S
.
Algorithm
Call a balanced string primitive if it cannot be partitioned into two non-empty balanced strings.
By keeping track of
balance
(the number of (
parentheses minus the number of )
parentheses), we can partition S
into primitive substrings S = P_1 + P_2 + ... + P_n
. Then, score(S) = score(P_1) + score(P_2) + ... + score(P_n)
, by definition.
For each primitive substring
(S[i], S[i+1], ..., S[k])
, if the string is length 2, then the score of this string is 1. Otherwise, it's twice the score of the substring (S[i+1], S[i+2], ..., S[k-1])
.- Time Complexity: , where is the length of
S
. An example worst case is(((((((....)))))))
. - Space Complexity: , the size of the implied call stack.
public int scoreOfParentheses(String S) {
return F(S, 0, S.length());
}
public int F(String S, int i, int j) {
// Score of balanced string S[i:j]
int ans = 0, bal = 0;
// Split string into primitives
for (int k = i; k < j; ++k) {
bal += S.charAt(k) == '(' ? 1 : -1;
if (bal == 0) {
if (k - i == 1)
ans++;
else
ans += 2 * F(S, i + 1, k);
i = k + 1;
}
}
return ans;
}
https://leetcode.com/problems/score-of-parentheses/discuss/141779/Java-8ms-11-lines-recursion-with-explanationpublic int scoreOfParentheses(String S) {return getScore(S.toCharArray(), 0, S.length() - 1);}private int getScore(final char[] chs, final int l, final int r) {int res = 0;int open = 0;int start = -1;for (int i = l; i <= r; i++) {if (chs[i] == '(') {open++;if (start == -1) {start = i;}} else {open--;if (open == 0) {if (i - start == 1) {res += 1;} else {res += 2 * getScore(chs, start + 1, i - 1);}start = -1;}}}return res;}
int i=0;
public int scoreOfParentheses(String S) {
int res=0;
while(i<S.length()){
char c=S.charAt(i++);
if (c=='('){
if (S.charAt(i)==')'){
res+=1;
i++;
} else res+=2*scoreOfParentheses(S);
}else return res;
}
return res;
}
time complexity : O(S.length()),
space complexity : between 1/2 * O(S.length()) ~ O(S.length())
X.
Solution1: Recursion
Time complexity: O(n^2)
https://zxi.mytechroad.com/blog/string/leetcode-856-score-of-parentheses/
int scoreOfParentheses(string S) {
return score(S, 0, S.length() - 1);
}
private:
int score(const string& S, int l, int r) {
if (r - l == 1) return 1; // "()"
int b = 0;
for (int i = l; i < r; ++i) {
if (S[i] == '(') ++b;
if (S[i] == ')') --b;
if (b == 0) // balanced
// score("(A)(B)") = score("(A)") + score("(B)")
return score(S, l, i) + score(S, i + 1, r);
}
// score("(A)") = 2 * score("A")
return 2 * score(S, l + 1, r - 1);
}
X. Build binary tree
https://medium.com/@poitevinpm/solution-to-leetcode-problem-856-score-of-parentheses-90dba4fd6f7b
public int scoreOfParentheses(String S) { TreeNode root = computeTreeNode(S); return root.computeScore(); } private TreeNode computeTreeNode(String S) { TreeNode current = new TreeNode(); TreeNode root = current; for (int i = 0; i < S.length(); i++) { if (S.charAt(i) == '(') { TreeNode child = new TreeNode(); child.setParent(current); current.addChild(child); current = child; } else { current = current.getParent(); } } return root; } class TreeNode { private List<TreeNode> children; private TreeNode parent; public TreeNode() { children = new ArrayList<>(); } public void addChild(TreeNode n) { children.add(n); } public void setParent(TreeNode p) { parent = p; } public TreeNode getParent() { return parent; } public int computeScore() { if (children.isEmpty()) { return 1; } int res = 0; for (TreeNode c : children) { res += c.computeScore(); } if (parent == null) { // root case return res; } return 2*res; } }