题目描述:
给定一个平衡括号字符串 S,按下述规则计算该字符串的分数:
() 得 1 分。
AB 得 A + B 分,其中 A 和 B 是平衡括号字符串。
(A) 得 2 * A 分,其中 A 是平衡括号字符串。
示例 1:
输入: “()”
输出: 1
示例 2:
输入: “(())”
输出: 2
示例 3:
输入: “()()”
输出: 2
示例 4:
输入: “(()(()))”
输出: 6
提示:
S 是平衡括号字符串,且只含有 ( 和 ) 。
2 <= S.length <= 50
方法1:
主要思路:解题链接汇总
(1)使用栈;
(2)使用0值作为栈中的占位符号;
(3)每次将可能相加的AB形式相加,存入结果中;
class Solution {
public:
int scoreOfParentheses(string S) {
stack<int> st;
for(char ch:S){
if(ch=='('){//在栈中压入占位值0
st.push(0);
}
else{
int cur=1;
if(st.top()==0){//说明当前是()形式
st.pop();//弹出占位值
}else{//说明当前是(A)形式
cur=st.top()*2;//乘以2倍
//弹出两个值,一个是A,另一个是占位值
st.pop();
st.pop();
}
if(!st.empty()&&st.top()!=0){//判断是否有AB形式
cur+=st.top();
st.pop();
}
st.push(cur);
}
}
return st.top();
}
};
//go语言实现
func scoreOfParentheses(S string) int {
st := make([]int,0,len(S)/2)
for _,ch:=range S {
if ch=='(' {
st=append(st,0)
}else {
cur:=1
if st[len(st)-1]==0 {
st=st[:len(st)-1]
}else{
cur=st[len(st)-1]*2
st=st[:len(st)-2]
}
if len(st)!=0&&st[len(st)-1]!=0 {
cur+=st[len(st)-1]
st=st[:len(st)-1]
}
st=append(st,cur)
}
}
return st[0]
}
方法2:
主要思路:
(1)统计每个()形式的深度;
(2)累加各个以()为核心的子字符串对应分数;
class Solution {
public:
int scoreOfParentheses(string S) {
int res=0;
int n=0;
for(int i=0;i<S.size();++i){
if(S[i]=='('){
++n;
}else {
--n;
if(S[i-1]=='('){
res+=1<<n;
}
}
}
return res;
}
};
//go实现
func scoreOfParentheses(S string) int {
res:=0
n:=0
for i:=0;i<len(S);i++ {
if S[i]=='(' {
n++
}else{
n--
if S[i-1]=='(' {
res+=1<<n
}
}
}
return res
}