LeetCode 856. Score of Parentheses
題目描述
- 英文:
Given a balanced parentheses stringS
, compute the score of the string based on the following rule:
-
()
has score 1 -
AB
has scoreA + B
, where A and B are balanced parentheses strings. -
(A)
has score2 * A
, where A is a balanced parentheses string. - 中文:
給定一個平衡括號字串S
,按下述規則計算該字串的分數:
-
()
得 1 分。 -
AB
得A + B
分,其中 A 和 B 是平衡括號字串。 -
(A)
得2 * A
分,其中 A 是平衡括號字串。
提示:
-
S
是平衡括號字串,且只含有(
和)
。 -
2 <= S.length <= 50
示例
- 示例 1:
輸入: "()" 輸出: 1
- 示例 2:
輸入: "(())" 輸出: 2
- 示例 3:
輸入: "()()" 輸出: 2
- 示例 4:
輸入: "(()(()))" 輸出: 6
題解
- 題解 1
利用棧解題,當遇到左半邊括號時壓進 -1 ,遇到右半邊括號時,判斷棧頂是否是 -1,如果不是則把棧頂的分數出棧,記錄到結果 score 中。 如果棧頂是 -1 ,則判斷 score 是否為 0,如果是,則證明是 () 這種情況,壓入分數1。否則,壓入 2 倍 score。
class Solution: def scoreOfParentheses(self, S): """ :type S: str :rtype: int """ stack = [] for i in S: if i == '(':# "("入棧 stack.append(-1) else: score = 0 while stack[-1] != -1:# 計分 score += stack.pop() stack.pop() if score == 0:# "()"的情況 stack.append(1) else:# "(A)" "AB" 的情況 stack.append(2 * score) return sum(stack)
- 題解 2
依然是棧的思想,但沒有用到棧。給定一個標記 flag,若 ‘(’ 則 flag 左移,若 ‘)’ 則 flag 右移,若遇到 () 則 將 flag 的值記錄到結果中去。
class Solution: def scoreOfParentheses(self, S): """ :type S: str :rtype: int """ score = 0 flag = 0 for i in range(len(S)): if S[i] == '(': if flag == 0:# "()"的情況 flag = 1 else:# "(A)" "AB" 的情況 flag = flag << 1 else: if S[i - 1] == '(': score += flag# 記錄到結果中 flag = flag >> 1 return score