1. 程式人生 > >Leetcode 856. Score of Parentheses 括號得分(棧)

Leetcode 856. Score of Parentheses 括號得分(棧)

Leetcode 856. Score of Parentheses 括號得分(棧)

題目描述

字串S包含平衡的括號(即左右必定匹配),使用下面的規則計算得分

  • () 得1分
  • AB 得A+B的分,比如()()得2分
  • (A) 得2A分, 比如(()())得2(1+1)分

測試樣例

Example 1:

Input: "()"
Output: 1
Example 2:

Input: "(())"
Output: 2
Example 3:

Input: "()()"
Output: 2
Example 4:

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

詳細分析

簡而言之,遇到右括號就一直出棧並累加到一個值直到遇到左括號,這個累加值就表示這對括號的得分。如此周而復始到字串結尾即可。

具體言之,遇到 ( 就入棧,這裡入一個毒藥值-1,然後遇到 ) 就一直出棧,累加到score,直到遇到毒藥值-1,最後把累加的score入棧,表示這對括號的最終得分。
最後計算棧中的結果之和即可。至於為什麼是棧結果和而不是棧頂一個值是因為輸入可能是()(),這種,最後棧中是| 1 | 1 |

演算法實現

class Solution {
public:
    int scoreOfParentheses(string S) {
        stack<int> s;
        int i=0;
        while(S[i]!=0){
            if(S[i]=='('){
                s.push(-1);
            }else if(S[i]==')'){
                int score = 0;
                if(s.top()==-1){
                    s.pop();
                    s.push(1);
                }else{
                   while(!s.empty()){
                        int t = s.top();
                        if(t==-1){
                            s.pop();
                            s.push(score);
                            break;
                        }
                        score+= t*2;
                        s.pop();
                    }
                }

            }
            i++;
        }
        int result = 0;
        while(!s.empty()){
            result += s.top();
            s.pop();
        }
        return result;
    }
};