用 Python 编写程序来计算 s 中不同子字符串的数量
pythonserver side programmingprogramming更新于 2026/1/18 16:12:17
假设我们有一个字符串 s,我们必须找出 s 中不同非空子字符串的数量。
因此,如果输入为 s = "abaa",则输出将为 8,因为子字符串为 ["a", "b", "ab", "ba", "aa", "aba", "baa", "abaa"]。
要解决这个问题,我们将遵循以下步骤 −
- trie := a new map
- n := s 的大小
- 对于范围为 0 到 n - 1 的 i,执行
- curr := trie
- 对于 i 到 n - 1 范围内的 j,执行
- c := s[j]
- 如果 c 不在 curr 中,则
- curr[c] := 一个新的映射
- curr := curr[c]
- curr["*"] := True
- q := 创建队列,并插入 trie
- ans := 0
- 当 q 非空时,执行
- ans := ans + 1
- t := q 的左项,并从中删除此项q
- 对于 t 中的每个 c,执行
- 如果 c 与 "*" 不同,则
- 在 q 末尾插入 t[c]
- 如果 c 与 "*" 不同,则
- 返回 ans - 1
示例
让我们看看下面的实现以便更好地理解 −
from collections import deque def solve(s): trie = {} n = len(s) for i in range(n): curr = trie for j in range(i, n): c = s[j] if c not in curr: curr[c] = {} curr = curr[c] curr["*"] = True q = deque([trie]) ans = 0 while q: ans += 1 t = q.popleft() for c in t: if c != "*": q.append(t[c]) return ans - 1 s = "abaa" print(solve(s))输入
"abaa"
输出
8
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/
打印 下一节:Python Pandas - 从具有特定时间序列频率的 DateTimeIndex 中提取分钟 ❯❮ 上一节:用 Python 编写程序,查找可以删除的最小子列表的长度,使总和可以被 k 整除

