跳到主要内容

2982.找出出现至少三次的最长特殊子字符串II

链接:2982.找出出现至少三次的最长特殊子字符串II
难度:Medium
标签:哈希表、字符串、二分查找、计数、滑动窗口
简介:返回在 s 中出现 至少三次 的 最长特殊子字符串 的长度,如果不存在出现至少三次的特殊子字符串,则返回 -1 。

题解 1 - python

  • 编辑时间:2024-05-30
  • 执行用时:461ms
  • 内存消耗:18.88MB
  • 编程语言:python
  • 解法介绍:哈希存储所有相同字符的串的长度,判断同类串的最大长度。
def get_longest(arr: Counter) -> int:
max_key = max(arr.keys())
if arr[max_key] >= 3:
return max_key
elif arr[max_key] * 2 + arr[max_key - 1] >= 3:
return max_key - 1
return max_key - 2
class Solution:
def maximumLength(self, s: str) -> int:
n = len(s)
map = defaultdict(Counter)
i = 0
while i < n:
j = i
while i < n and s[j] == s[i]: i += 1
map[s[j]][i - j] += 1
vmax = max([get_longest(arr) for arr in map.values()])
return vmax if vmax else -1