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

LeetCode 2416: Sum of Prefix Scores of Strings

·1 分鐘· ·
LeetCode Hard Trie String Counting
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: hard 第一次嘗試:2026-09-13

  • 提交紀錄:Accepted(一次通過)

解題思路
#

一個前綴的分數 = 有幾個單字以它開頭。每個單字的答案 = 它所有前綴的分數總和。

在 Trie 上,一個節點代表一個前綴,「有幾個單字以它開頭」就是「有幾個單字經過這個節點」。所以:

  1. 建 Trie 時,每經過一個節點就把它的計數加 1。
  2. 每個單字再走一次 Trie,把沿路的計數加起來。

我的解法
#

class Solution:
    def sumPrefixScores(self, words: List[str]) -> List[int]:
        trie = {}                          # char -> [經過次數, 子節點]
        for word in words:
            node = trie
            for ch in word:
                if ch not in node:
                    node[ch] = [0, {}]
                node[ch][0] += 1
                node = node[ch][1]

        res = []
        for word in words:
            total, node = 0, trie
            for ch in word:
                total += node[ch][0]
                node = node[ch][1]
            res.append(total)
        return res

複雜度
#

時間 O(總長度),建 Trie 和查詢各走一次。空間 O(總長度)。

我交的時候用了 293MB 記憶體:每個節點是 [count, dict],Python 的小 dict 本身就有固定成本。用 class 搭配 __slots__ 可以省一些。

要特別避免的錯誤
#

  • 對每個前綴重新掃所有單字:O(n · L^2) 以上,太慢。
  • 計數加在子節點建立的時候而不是每次經過的時候:重複出現的前綴會少算。

面試口說整理
#

Trie 的每個節點代表一個前綴,以這個前綴開頭的單字數,就是經過這個節點的單字數。所以我建 Trie 時在每個經過的節點上計數加 1,之後每個單字再走一次 Trie,把沿路的計數加總就是答案。建立和查詢都是總長度的線性時間。

相關文章

LeetCode 2781: Length of the Longest Valid Substring
·2 分鐘
LeetCode Hard Sliding-Window Hash-Table String Trie
LeetCode 2781 解題筆記:禁字最長只有 10,每個右端只檢查最後 10 個字元組成的後綴;找到禁字就把左端推到它後面,要找最短的那個(最靠右的起點)
LeetCode 3518: Smallest Palindromic Rearrangement II
·2 分鐘
LeetCode Hard Math Combinatorics Counting Hash-Table String
LeetCode 3518 解題筆記:回文由左半邊決定,變成「多重集合的第 k 個排列」;逐位試每個字元,用排列數判斷第 k 個落在哪個分支,排列數可以 O(1) 更新
LeetCode 940: Distinct Subsequences II
·1 分鐘
LeetCode Hard Dynamic-Programming String
LeetCode 940 解題筆記:依最後一個字元分類;以 c 結尾的不同子序列 = 目前所有不同子序列後面接 c,再加上 c 本身,直接覆蓋舊的值
LeetCode 1178: Number of Valid Words for Each Puzzle
·1 分鐘
LeetCode Hard Bit-Manipulation Hash-Map Trie
LeetCode 1178 解題筆記:單字只在乎用了哪些字母,轉成 26-bit 遮罩計數,再枚舉謎題遮罩的所有子集合
LeetCode 1320: Minimum Distance to Type a Word Using Two Fingers
·1 分鐘
LeetCode Hard Dynamic-Programming State-Machine String
LeetCode 1320 解題筆記:打完 word[i] 時,一定有一根手指在 word[i] 上,狀態只要記另一根手指在哪;dp[other] 是另一根手指在 other 的最小距離
LeetCode 902: Numbers At Most N Given Digit Set
·1 分鐘
LeetCode Hard Dynamic-Programming Digit-Dp Math Binary-Search String
LeetCode 902 解題筆記:數位 DP,狀態是 (pos, tight, started);還沒開始時可以跳過這一位,代表位數比 n 少的數