📅  最后修改于: 2023-12-03 15:40:14.630000             🧑  作者: Mango
给定一个包含小写字母的字符串,找到最大长度的子串,使其包含字符串中所有出现过的字符,且子串没有重叠部分。例如,对于字符串 "abcdecfghk",要求包含所有出现过的字符,可以找到子串 "cde" 或者 "decfgh",但最大长度的子串是 "decfgh"。
首先,我们需要保证子串中包含了所有出现的字符,可以用一个hashmap来记录,将字符串中每个字符出现的次数记录下来。然后我们从左到右扫描整个字符串,在第一个符合条件的子串长度为i时停止,记录最大长度。
count_map = {}
for c in s:
if c not in count_map:
count_map[c] = 1
n = len(s)
left = 0
count = len(count_map)
res = 0
for right in range(n):
if s[right] in count_map:
count_map[s[right]] -= 1
if count_map[s[right]] == 0:
count -= 1
while count == 0:
if s[left] in count_map:
count_map[s[left]] += 1
if count_map[s[left]] > 0:
count += 1
if right - left + 1 == i:
res = max(res, i)
left += 1
该算法的时间复杂度为O(n^2)
class Solution:
def maxUniqueSplit(self, s: str) -> int:
n = len(s)
count_map = {}
for c in s:
if c not in count_map:
count_map[c] = 1
left = 0
count = len(count_map)
res = 0
for right in range(n):
if s[right] in count_map:
count_map[s[right]] -= 1
if count_map[s[right]] == 0:
count -= 1
while count == 0:
if s[left] in count_map:
count_map[s[left]] += 1
if count_map[s[left]] > 0:
count += 1
if right - left + 1 == i:
res = max(res, i)
left += 1
return res