无重复字符的最长子串
一、思路
使用贪心思想,首先从第一个字符开始往后遍历,只要碰到已经出现过的字符我们就必须从之前出现该字符的index+1处开始重新往后,更新当前最长子串的起始字符索引start_index
二、python实现
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
res_len, start_index, s_len = 0, 0, len(s)
occur_dict = {}
for i in range(s_len):
start_index = max(start_index, occur_dict.get(s[i], -1)+1)
res_len = max(res_len, i - start_index + 1)
occur_dict[s[i]] = i
return res_len
变量意义:
res_len:最长子串的长度
start_index:当前最长子串的起始索引
occur_dict:字典,用来存放字符第一次出现时的索引