题目描述
给定一个平衡括号字符串 S
,按下述规则计算该字符串的分数:
()
得 1 分。AB
得A + B
分,其中 A 和 B 是平衡括号字符串。(A)
得2 * A
分,其中 A 是平衡括号字符串。
示例 1:
输入: "()"
输出: 1
示例 2:
输入: "(())"
输出: 2
示例 3:
输入: "()()"
输出: 2
示例 4:
输入: "(()(()))"
输出: 6
提示:
S
是平衡括号字符串,且只含有(
和)
。2 <= S.length <= 50
题解思路
我的题解思路就是注释,这题面试到了,没做过,想了好久才想出来的解法,下次再遇到应该很快就能写出来。
代码
class Solution {
public int scoreOfParentheses(String s) {
//score[i]存储第i层的值,从第一层开始,字符串长度最大为50,故最多为25层
int[] score = new int[26];
char[] chars = s.toCharArray();
//当前层数,没经过'('层数+1,否则层数-1
int level = 0;
//存储最大层数
int maxLevel = 0;
int len = s.length();
for (int i = 0; i < len; i++) {
//当前遍历的字符
char temp = chars[i];
//如果遇到左括号,层数加一
if (temp == '(') {
level++;
//保存最大层数
maxLevel = Math.max(level, maxLevel);
} else {
//遇到右括号且前一个值char[i - 1]不为右括号,当前层值+1
if (chars[i - 1] != ')') {
score[level] += 1;
}
//遇到右括号层数减一。
level--;
}
}
//结果
int res = 0;
//从最大层一直遍历到第一层,如果不是第一层,res加上当前层的值然后乘以二,如果到了第一层,只需要加上当前层的值,无需乘2。
while (maxLevel > 0) {
res += score[maxLevel];
if (maxLevel != 1) {
res *= 2;
}
maxLevel--;
}
return res;
}
}
时间复杂度
O(N)
官方题解-统计核心的数目
- 官方题解和我的大体思路很像,但是代码优化了很多。
代码
class Solution {
public int scoreOfParentheses(String s) {
int res = 0;
int depth = 0;
int len = s.length();
for (int i = 0; i < len; i++) {
if (s.charAt(i) == '(') {
depth++;
} else {
depth--;
if (s.charAt(i - 1) == '(') {
res += 1 << depth;
}
}
}
return res;
}
}
时间复杂度
O(n)