leetcode 856. 括號的分數
阿新 • • 發佈:2021-06-13
給定一個平衡括號字串S,按下述規則計算該字串的分數:
() 得 1 分。
AB 得A + B分,其中 A 和 B 是平衡括號字串。
(A) 得2 * A分,其中 A 是平衡括號字串。
示例 1:
輸入: "()"
輸出: 1
示例 2:
輸入: "(())"
輸出: 2
示例3:
輸入: "()()"
輸出: 2
示例4:
輸入: "(()(()))"
輸出: 6
提示:
S是平衡括號字串,且只含有(和)。
2 <= S.length <= 50
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/score-of-parentheses
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
public int scoreOfParentheses(String s) { Stack<Integer> stack = new Stack<>(); char[] arr = s.toCharArray(); int length = s.length(); for (int i = 0; i < length; i++) { char c = arr[i]; if (c == '(') { stack.push(0); } else { if (stack.peek() == 0) { stack.pop(); stack.push(1); } else { int sum = 0; int value; while ((value = stack.pop()) != 0) { sum+= value; } stack.push(sum << 1); } } } int sum = 0; while (!stack.isEmpty()) { sum += stack.pop(); } return sum; }