首页 > 其他 > 详细

【字符串】856. 括号的分数

时间:2020-05-04 13:19:13      阅读:52      评论:0      收藏:0      [点我收藏+]

题目:

技术分享图片

 

 

解答:

技术分享图片

 

 

 1 class Solution {
 2 public:
 3     int scoreOfParentheses(string S) 
 4     {
 5         stack<int> stack;
 6         stack.push(0); // The score of the current frame
 7 
 8         for (int i = 0; i < S.size(); i++) 
 9         {
10             char c = S[i];
11             if (c == ()
12                 stack.push(0);
13             else 
14             {
15                 int v = stack.top();
16                 stack.pop();
17                 int w = stack.top();
18                 stack.pop();
19                 stack.push(w + std::max(2 * v, 1));
20             }
21         }
22 
23         return stack.top();
24     }
25 };

 

方法三:统计核心的数目

事实上,我们可以发现,只有 () 会对字符串 S 贡献实质的分数,其它的括号只会将分数乘二或者将分数累加。因此,我们可以找到每一个 () 对应的深度 x,那么答案就是 2^x 的累加和。

 1 class Solution {
 2 
 3     public int scoreOfParentheses(String S) {
 4         int ans = 0, bal = 0;
 5         for (int i = 0; i < S.length(); ++i) {
 6             if (S.charAt(i) == () {
 7                 bal++;
 8             } else {
 9                 bal--;
10                 if (S.charAt(i-1) == ()
11                     ans += 1 << bal;
12             }
13         }
14 
15         return ans;
16     }
17 };

 

【字符串】856. 括号的分数

原文:https://www.cnblogs.com/ocpc/p/12826198.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!