856. Score of Parentheses(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/84204767

题目:

Given a balanced parentheses string S, compute the score of the string based on the following rule:
() has score 1
AB has score A + B, where A and B are balanced parentheses strings.
(A) has score 2 * A, where A is a balanced parentheses string.

Example 1:

Input: "()" 
Output: 1 

Example 2:

Input: "(())" 
Output: 2 

Example 3:

Input: "()()" 
Output: 2 

Example 4:

Input: "(()(()))" 
Output: 6  

Note:
S is a balanced parentheses string, containing only ( and ).
2 <=S.length <= 50

解释:
这种括号的问题,一看就是用栈来做。
python代码:

class Solution(object):
    def scoreOfParentheses(self, S):
        """
        :type S: str
        :rtype: int
        """
        stack=[]
        for s in S :
            if s=='(':
                stack.append(s)
            else:
                pre=stack.pop()
                if pre=="(":
                    stack.append(1)
                else:
                    current_sum=pre
                    while stack[-1]!='(':
                        current_sum+=stack.pop()
                    stack.pop()
                    stack.append(current_sum*2)
        return sum(stack)

python的list没有变量类型的限制,可以随便放数字或者 char,但是c++的stack要设置类型的,怎么办?只能把(用数字0来表示。
c++代码:

#include<stack>
using namespace std;
class Solution {
public:
    int scoreOfParentheses(string S) {
        stack<int> _stack;
        for (auto s:S)
        {  
            if (s=='(')
                _stack.push(0);
            else
            {
                int pre=_stack.top();
                _stack.pop();
                if (pre==0)
                    _stack.push(1);
                else
                {
                    int cur_sum=pre;
                    while(_stack.top()!=0)
                    {
                        cur_sum+=_stack.top();
                        _stack.pop();
                    }
                    _stack.pop();
                    _stack.push(2*cur_sum);
                }
            }    
        }
        int result=0;
            while(!_stack.empty())
            {
                result+=_stack.top();
                _stack.pop();
            }
            return result;
    }
};

解释:

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/84204767
今日推荐