467. 环绕字符串中唯一的子字符串

exiaohu 于 2022-05-25 发布

题目链接:467. 环绕字符串中唯一的子字符串

遍历的状态可以用一个字典来描述,字典的键是 a-z 共 26 个字母,值为以该字母开头的最长合法字符串的长度。

from collections import defaultdict


class Solution:
    def findSubstringInWraproundString(self, p: str) -> int:
        prefix, i = defaultdict(int), 1

        def add_prefix(segment: str):
            for i in range(min(len(segment), 26)):
                prefix[segment[i]] = max(len(segment) - i, prefix[segment[i]])

        while i < len(p):
            if (ord(p[i]) - ord(p[i - 1]) + 26) % 26 != 1:
                add_prefix(p[:i])
                p, i = p[i:], 0
            i += 1
        if p:
            add_prefix(p)

        return sum(prefix.values())