LeetCode856. 括號的分數 c++(最詳細的思路解法!!!)

給定一個平衡括號字符串 S,按下述規則計算該字符串的分數:

() 得 1 分。
AB 得 A + B 分,其中 A 和 B 是平衡括號字符串。
(A) 得 2 * A 分,其中 A 是平衡括號字符串。

示例 1:

輸入: “()”
輸出: 1
示例 2:

輸入: “(())”
輸出: 2
示例 3:

輸入: “()()”
輸出: 2
示例 4:

輸入: “(()(()))”
輸出: 6

提示:

S 是平衡括號字符串,且只含有 ( 和 ) 。
2 <= S.length <= 50

思路一:
對於給定的平衡括號字符串,只要遍歷這個字符串,定義int型變量count_left來記錄左括號的個數,int型變量爲count來記錄總的分數,從第一個元素開始,遇到‘(’,count_left就加1,遇到‘)’就看其前面的元素是不是‘(’,如果是,則說明要麼就是簡單的“()”型,要麼就是 “(A)”型,count加上2^(count_left-1),然後count_left減少1,如果不是,直接減少1。直到遍歷完整個序列。然後返回count,即爲總的分數。

代碼如下:

class Solution {
public:
    int scoreOfParentheses(string S) {
        int count = 0;
        int count_left = 0;
        for(int i = 0;i<S.size();i++){
            if(S[i]=='('){
                count_left++;
            }
            else{
                if(S[i-1]=='('){
                    count+=pow(2,count_left-1);
                    count_left--;
                }
                else{
                    count_left--;
                }
            }
        }
        return count;
    }
};

思路二:
用棧解決的話,如果遇到左括號,則入棧。如果遇到右括號,判斷棧頂是不是右括號,如果是則說明是(),出棧並壓數字1;否則說明是(A)型,將內部數字全部加起來再次入棧。最後棧內是各種數字,加起來就可以了。

代碼如下:

/*class Solution {
public:
    int scoreOfParentheses(string S) {
        stack<string> s;
        for(char& i : S) {
            if(i == '(') {
                s.push("(");
            } else {
                if(!s.empty() && s.top() == "(") {
                    s.pop();
                    s.push("1");
                } else {
                    int sum = 0;
                    while(!s.empty() && s.top() != "(") {
                        sum += stoi(s.top());
                        s.pop();
                    }
                    if(!s.empty()) {
                        s.pop();
                    }
                    s.push(to_string(sum * 2));
                }
            }
        }
        int res = 0;
        while(!s.empty()) {
            res += stoi(s.top());
            s.pop();
        }
        return res;
    }
};*/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章