-
给定一个平衡括号字符串
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) { unsigned int B=0; stack<string>s; while(B<S.length()) { char ch[2]; ch[0]=S[B]; ch[1]='\0'; string os=ch; if(os!=")") { s.push(os); } else { if(s.top()=="(") { s.pop();os="1";s.push(os); } else { int a=0; while(s.top()!="("&&!s.empty()) { a=a+atoi(s.top().c_str()); s.pop(); } if(s.top()=="(") { int b=2*a; s.pop(); s.push(to_string(b)); } else { int b=a; s.push(to_string(b)); } } } B++; } int sum=0; while(!s.empty()) { sum=sum+atoi(s.top().c_str()); s.pop(); } return sum; } };
leetcode856括号的分数c++
猜你喜欢
转载自blog.csdn.net/HeXiQuan123/article/details/80793554
今日推荐
周排行