请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3
复杂度两个方法都一样
时间复杂度O(n)
空间复杂度O(1)
一、动态规划+哈希表
条件是当前的子字符串的头和尾不是重复字符,靠重复字符的位置相减,得到的结果与子字符串长度tmpmax比较
func lengthOfLongestSubstring(s string) int {
remap := make(map[int32]int)
retmax, tmpmax := 0, 0
for i, v := range s {
if j, ok := remap[v]; ok && tmpmax >= i-j {
tmpmax = i - remap[v]
} else {
tmpmax += 1
}
remap[v] = i
if tmpmax > retmax {
retmax = tmpmax
}
}
return retmax
}
二、双指针+哈希表-维护最左边界
start是最左边界,每当遇到重复字符时,当前字串就可不再维护,start就往右移到下一个最左子字符串的开始,i-start就是长度
func lengthOfLongestSubstring(s string) int {
start, res := -1, 0
dic := map[int32]int{}
for i, v := range s {
if vfd, ok := dic[v]; ok {
start = max(start, vfd)
}
dic[v] = i
res = max(res, i-start)
}
return res
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}