题目要求:
首尝试解题思路
- 首先计算每个字符在当前位置及往前出现的次数,
比如:‘aababcba’
则出现次数为[1,2,1,3,2,1,3,4]
- 第二步使用滑窗:
- 判断滑窗内是否出现频率总和与滑窗长度相等
- 若相等则判断此长度为最大长度
- 若不相等则left向右移
- 右移前判断右移后窗口内是否存在该字符,若存在则该字符频率-1
- 右移直到频率总和与滑窗长度相等
此时可解答出来,但时间复杂度为n的3次方,超过了时间限制,哭。。。
def len_str(s):
counter = []
for i in range(len(s)):
if i == 0:
counter.append(1)
elif s[i] in s[:i]:
temp = s[i]
cnt = 0
for j in s[:i+1]:
if j == temp:
cnt += 1
counter.append(cnt)
elif s[i] not in s[:i]:
counter.append(1)
# print(counter, len(counter))
left = 0
right = 0
if len(s) == 0:
res = 0
else:
res = 1
while right < len(s) and left < len(s):
# 滑动窗口并判断窗口内总和是否等于 right-left+1
sum_RL = 0
if right == left and right < len(s):
sum_RL = counter[right]
else:
for i in range(left, right + 1):
sum_RL += counter[i]
if sum_RL == right - left + 1:
res = max(res, right-left+1)
right += 1
else:
for i in range(left+1, len(s)):
if s[i] == s[left]:
counter[i] -= 1
left += 1
# print('s[right]', 'right', 'left', 'counter[i]')
# print(res)
return res
LeetCode通过的思路
- 滑窗法中判断待右移字符是否存在窗口内,若存在则left+1,直到right==left
def len_str(s):
left = 0
right = 0
if len(s) == 0:
res = 0
else:
res = 1
while right+1 < len(s) and left < len(s):
# 滑动窗口并判断下个字符是否出现在窗口内
right += 1
cnt = 0
while left <= right:
if s[right] in s[left:right]:
left += 1
print(s[right], left)
if s[right] not in s[left:right]:
break
print(right, left)
res = max(res, right - left + 1)
return res