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

LeetCode 3805: Count Caesar Cipher Pairs

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

基本資料
#

難易度: medium 第一次嘗試:2026-01-11

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

解題思路
#

兩個字串可以透過整串平移變成一樣 ⇔ 每個位置跟第一個字母的差(mod 26)都一樣。

所以把每個字串正規化:整串平移到第一個字母是 a,也就是每個字母記成 (c - word[0]) mod 26。等價的字串會得到一樣的結果,用雜湊表數每種結果有幾個,配對數是 c × (c - 1) / 2。

我的解法
#

class Solution:
    def countPairs(self, words: List[str]) -> int:
        cnt = Counter()
        pairs = 0
        for w in words:
            key = tuple((ord(c) - ord(w[0])) % 26 for c in w)   # 平移到第一個字母是 a
            pairs += cnt[key]                      # 跟前面每個等價的配一對
            cnt[key] += 1
        return pairs

我原本是真的組出平移後的字串,用 chr 和條件判斷處理繞回來的情況,最後用 v * (v - 1) / 2 算(浮點除法,再轉回整數)。用 % 26 的 tuple 當 key 比較乾淨,也不會碰到浮點數。

複雜度
#

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

要特別避免的錯誤
#

  • 平移要繞回來:z 的下一個是 a,用 % 26。
  • 配對數用整數運算。

面試口說整理
#

兩個字串凱薩等價,就是每個字母跟第一個字母的差(mod 26)都一樣。所以我把每個字串正規化成這個差的序列當 key,邊掃邊數前面有幾個同樣的 key,加起來就是配對數。時間 O(n · m)。

相關文章

LeetCode 2131: Longest Palindrome by Concatenating Two Letter Words
·1 分鐘
LeetCode Medium Greedy Hash-Table String Counting
LeetCode 2131 解題筆記:每個字跟它的反轉配成一對放兩邊;本身是回文的字也能兩兩配對,只有剩下的一個能放正中間
LeetCode 3518: Smallest Palindromic Rearrangement II
·2 分鐘
LeetCode Hard Math Combinatorics Counting Hash-Table String
LeetCode 3518 解題筆記:回文由左半邊決定,變成「多重集合的第 k 個排列」;逐位試每個字元,用排列數判斷第 k 個落在哪個分支,排列數可以 O(1) 更新
LeetCode 1814: Count Nice Pairs in an Array
·1 分鐘
LeetCode Medium Array Hash-Table Math Counting
LeetCode 1814 解題筆記:把條件移項成 nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]),按這個值分組數 pair,記得取模
LeetCode 2516: Take K of Each Character From Left and Right
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table String
LeetCode 2516 解題筆記:從兩端拿等於中間留一段;留下的每種字元最多是總數 − k,找最長的這種中間視窗
LeetCode 1461: Check If a String Contains All Binary Codes of Size K
·1 分鐘
LeetCode Medium Hash-Table String Bit-Manipulation Rolling-Hash
LeetCode 1461 解題筆記:把所有長度 k 的子字串丟進集合,大小等於 2^k 就成立;最後一個起點是 len(s) - k
LeetCode 1016: Binary String With Substrings Representing 1 To N
·2 分鐘
LeetCode Medium Sliding-Window String Bit-Manipulation Hash-Table
LeetCode 1016 解題筆記:s 最多 1000 個字元,長度固定時的子字串數量有限,n 太大一定是 False;從 n 往下檢查會很快失敗,或從每個起點往右最多延伸 30 位收集所有 <= n 的值