856括号的分数 Posted on 2020-05-12 Words count in article: 230 | Reading time ≈ 1 856括号的分数 又是万恶的括号题!但是思路差不多 如果是左括号,那么入栈,用0模拟 如果是右括号,那么判断栈顶是不是等于0 如果等于0,那么就加一分,0出栈,1入栈 如果不等于0,说明中间含有数字。那么就把中间的数字全部取出来,计算出他们的和 因为不管中间是多少数字,还是要和(匹配的,所以最后还要pop,然后把和的两倍入栈 代码 1234567891011121314151617181920212223242526272829303132333435363738#include<bits/stdc++.h>using namespace std;class Solution {public: int scoreOfParentheses(string S) { stack<int>s; for(auto c:S) { if(c=='(') s.push(0); else { if(s.top()==0) { s.pop(); s.push(1); }else{ int temp = 0; while(s.top()!=0) { temp+=s.top(); s.pop(); } s.pop(); s.push(temp*2); } } } int ans = 0; while(!s.empty()) { ans+=s.top(); s.pop(); } return ans; }}; -------------本文结束,感谢您的阅读------------- Post author: Jason Post link: https://jasonxqh.github.io/2020/05/12/856%E6%8B%AC%E5%8F%B7%E7%9A%84%E5%88%86%E6%95%B0/ Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.