版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_42183408/article/details/89094299
leetcode网站地址:https://leetcode-cn.com/problemset/all/
题目
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
**输入:** "abcabcbb"
**输出:** 3
**解释:** 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
**输入:** "bbbbb"
**输出:** 1
**解释:** 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
**输入:** "pwwkew"
**输出:** 3
**解释:** 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
解答
def lengthOfLongestSubstring(s):
#最长子串
max_number = 0
#目前子串
number = 0
test = ''
for i in s:
#如果还没重复
if i not in test:
#加入
test += i
#目前子串长度加一
number += 1
else:
#判断目前最长子串是否多于记录
if number >= max_number:
#如果多于,则更新最长子串
max_number = number
#index方法检索字符串,返回开始索引值
index = test.index(i)
#从下一个开始检索
test = test[(index+1):] + i
#更新目前子串
number = len(test)
#最后判断是否更新最长子串
if number > max_number:
max_number = number
#返回最长子串
return max_number
详细的注释已经在代码中了,下次见!