1. 程式人生 > >棧---括號的分數

棧---括號的分數

  1. 題目 給定一個平衡括號字串 S,按下述規則計算該字串的分數: 給定一個平衡括號字串 S,按下述規則計算該字串的分數: () 得 1 分。 AB 得 A + B 分,其中 A 和 B 是平衡括號字串。 (A) 得 2 * A 分,其中 A 是平衡括號字串。
  2. 示例
輸入: "()"
輸出: 1
輸入: "(())"
輸出: 2
輸入: "()()"
輸出: 2
輸入: "(()(()))"
輸出: 6
  1. 提示 S 是平衡括號字串,且只含有 ( 和 ) 。 2 <= S.length <= 50
  2. 程式碼實現 a.資料結構:運算元棧,運算子棧; b.遍歷平衡括號字串,因其只有(和),則只有4種情形,依次為()、((、)(、((。 ():將1壓入運算元棧; ((:將壓入運算子棧; )(:將+壓入運算子棧; ((:執行
    運算,分兩種情形:若棧頂元素為*,則去運算元棧棧頂元素直接進行運算,若棧頂元素不為*,則需要先執行上方的所有+運算,再執行*運算。 c.執行運算子棧所有運算; d.運算元棧棧頂運算即為所求。
import java.util.Stack;

class Solution {
    public int scoreOfParentheses(String S) {
        Stack<Integer> number = new Stack<>();
        Stack<Character> operation = new Stack<>();
        for(int i=0;i<S.length()-1;i++){
            char current = S.charAt(i);
            char next = S.charAt(i+1);
            if(current=='('&&next==')'){
                number.push(1);
            }
            if(current=='('&&next=='('){
                operation.push('*');
            }
            if(current==')'&&next=='('){
                operation.push('+');
            }
            if(current==')'&&next==')'){
                char op =operation.pop();
                //執行*前,需要先執行前面所有的+運算
                while (op!='*'){
                    int num1 = number.pop();
                    int num2 = number.pop();
                    number.push(num1+num2);
                    op = operation.pop();
                }
                number.push(number.pop()*2);
            }
        }
        while (!operation.empty()){
            char op = operation.pop();
            //前面遍歷只到S.length()-1,所以仍然可能存在棧頂元素為*的情況
            if(op=='*'){
                int numTop = number.pop();
                numTop = numTop*2;
                number.push(numTop);
            }
            if(op=='+'){
                int num1 = number.pop();
                int num2 = number.pop();
                number.push(num1+num2);
            }
        }
        return  number.peek();
    }
}

5.總結 程式即人思維的體現。看到這個題目你會怎麼樣計算,程式也就是反映你的計算過程而已。