最大不重复子串是经典的滑动窗口问题
思路:
mp记录每个字符出现的最大索引位置
start记录当前不重复子串的起始索引位置
先用Python实现一遍
def lengthOfLongestSubstring(s: str) -> int:
if len(s) <= 1: return len(s)
mp, start, res = {}, 0, 0
for i, v in enumerate(s):
if v in mp and mp[v]>=start:
start = mp[v]+1
mp[v] = i
res = max(res, i-start+1)
return res
完全相同的思路再用Go实现一遍
func lengthOfLongestSubstring(s string) int {
if len(s) <= 1 {return len(s)}
mp := make(map[rune]int)
start, res := 0, 0
for i, v := range s {
if _, ok := mp[v]; ok && mp[v] >= start {
start = mp[v] + 1
}
mp[v] = i
if i-start+1 > res {
res = i-start+1
}
}
return res
}
leetcode结果如下 (Python总是被碾压, 哭, 不过代码更精简, 笑)