↓快轉到主要內容
  1. LeetCode/

LeetCode 3707: Equal Score Substrings

·1 分鐘· ·
LeetCode Easy Prefix-Sum String
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2025-10-11

  • 提交紀錄:Wrong Answer → Accepted

解題思路
#

先算總分,再從左往右累加左邊的分數,右邊就是 total - left(Prefix Sum 模板二)。分割點要讓兩邊都非空,所以最後一個字元之前就要停。

我的嘗試
#

第一版直接用 ord(char) 當分數。ord 是字母順序加 96,兩邊長度不同時會多出不同的 96 × 長度。例如 "bac":"ba" 是 2 + 1 = 3、"c" 是 3,答案是 True;用 ord 算是 195 對 99,回傳 False。改成 ord(char) - ord("a") + 1 就 AC 了。

正確解法
#

class Solution:
    def scoreBalance(self, s: str) -> bool:
        scores = [ord(c) - ord("a") + 1 for c in s]
        total, left = sum(scores), 0
        for x in scores[:-1]:
            left += x
            if left * 2 == total:
                return True
        return False

複雜度
#

時間 O(n),空間 O(n)。

要特別避免的錯誤
#

  • 分數是字母順序 1 到 26,要減掉 ord("a") 再加 1。
  • 右邊不能是空的,最後一個字元不能當分割點。

面試口說整理
#

我先算整個字串的分數,再從左邊開始累加,左邊剛好是總分一半時就能切。分數是字母順序,要用 ord(c) - ord('a') + 1。時間 O(n)。

相關文章

LeetCode 3606: Coupon Code Validator
·1 分鐘
LeetCode Easy Hash-Table String Sorting
LeetCode 3606 解題筆記:先過濾合法的優惠券,再用(類別順序, code)排序;字元範圍要包含 z、Z、9
LeetCode 1768: Merge Strings Alternately
·1 分鐘
LeetCode Easy Two-Pointers String
LeetCode 1768 解題筆記:兩個指針輪流取字元,短的用完後接上長的剩下部分
LeetCode 3136: Valid Word
·1 分鐘
LeetCode Easy String
LeetCode 3136 解題筆記:長度至少 3、只能有英數字元、至少一個母音、至少一個子音;數字不是子音
LeetCode 1189: Maximum Number of Balloons
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 1189 解題筆記:每個字母可以組幾個 balloon 是 次數 // 需要數,l 和 o 需要兩個,取最小值
LeetCode 1078: Occurrences After Bigram
·1 分鐘
LeetCode Easy String
LeetCode 1078 解題筆記:切成單字後檢查每個連續三個單字,前兩個符合 first 和 second 就收第三個
LeetCode 1047: Remove All Adjacent Duplicates In String
·1 分鐘
LeetCode Easy String Stack
LeetCode 1047 解題筆記:stack 頂端跟目前字元相同就一起消掉,否則放進 stack;消掉之後新的頂端可能又能跟下一個消