🔗 🟢 3803. Count Residue Prefixes

Problem Statement

題目簡述

給定一個僅包含小寫英文字母的字串 ss。
若 ss 的某個非空前綴中,相異字元數恰好等於該前綴長度模 33 的餘數(即 len⁡(prefix) mod 3\operatorname{len}(\text{prefix}) \bmod 3),則稱其為 殘差前綴(residue prefix)。
請回傳 ss 中殘差前綴的總數。

Constraints

約束條件

  • 1≤∣s∣≤1001 \le |s| \le 100
  • ss 僅包含小寫英文字母

思路:雜湊集合與剪枝

由左到右依序枚舉每個長度為 ii(1≤i≤∣s∣1 \le i \le |s|)的非空前綴,並用 雜湊表(Hash Table)(集合)即時維護目前前綴出現過的相異字元數。

關鍵觀察

任意前綴長度對 33 取餘的結果只會落在 {0,1,2}\{0, 1, 2\},永遠小於 33;而隨著前綴向右延伸,相異字元數具有單調不減的性質。

因此,一旦目前集合中的相異字元數達到 33,後續所有更長的前綴其相異字元數必定 ≥3\ge 3,絕不可能再滿足等於 i mod 3i \bmod 3 的條件,此時直接 剪枝(Pruning) 跳出迴圈即可。

複雜度分析

  • 時間複雜度:O(n)\mathcal{O}(n),其中 n=∣s∣n = |s|。每個字元至多被走訪一次,且若提早出現第 33 種字元便立即終止。
  • 空間複雜度:O(1)\mathcal{O}(1),集合在大小達到 33 時就會跳出,最多僅儲存 33 個字元。

Code

1
2
3
4
5
6
7
8
9
10
class Solution:
def residuePrefixes(self, s: str) -> int:
ans = 0
st = set()
for i, c in enumerate(s, start=1):
st.add(c)
if len(st) >= 3: # Pruning
break
ans += i % 3 == len(st)
return ans

寫在最後

Cover Image Credit

The cover image was created by @NekoArc17. All rights belong to the original artist.

If you are the copyright holder and believe this usage is inappropriate, please contact me by email or leave a comment. I will remove the image promptly.