给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
使用两个指针,分别为头指针和尾指针。
代码
func lengthOfLongestSubstring(s string) int {
if len(s) == 0 {
return 0
}
hashMap := make(map[byte]int)
leftP := 0
rightP := 0
result := 1
for rightP < len(s) {
_, ok := hashMap[s[rightP]]
if !ok {
hashMap[s[rightP]] = 1
rightP++
if (rightP - leftP) > result {
result = rightP - leftP
}
}else{
for s[leftP] != s[rightP] {
leftP++
}
leftP++
rightP = leftP
hashMap = make(map[byte]int)
}
}
return result
}
但是性能表现却很差
执行用时:260 ms, 在所有 Go 提交中击败了5.16%的用户
内存消耗:6.8 MB, 在所有 Go 提交中击败了5.34%的用户
通过测试用例:987 / 987
这是滑动窗口的一般思路,题解也是这个做法,不懂为何性能这么差!
优化了之前的代码,性能大大提高
func lengthOfLongestSubstring(s string) int {
if len(s) == 0 {
return 0
}
hashMap := map[byte]int{}
leftP := 0
rightP := 0
result := 1
for rightP < len(s) {
if hashMap[s[rightP]] == 0 {
hashMap[s[rightP]]++
rightP++
if (rightP - leftP) > result {
result = rightP - leftP
}
}else{
for s[leftP] != s[rightP] {
// 头指针移动的同时删除map中相应元素
delete(hashMap, s[leftP])
leftP++
}
delete(hashMap, s[leftP])
leftP++
}
}
return result
}
性能
执行用时:12 ms, 在所有 Go 提交中击败了40.79%的用户
内存消耗:2.6 MB, 在所有 Go 提交中击败了67.64%的用户
通过测试用例:987 / 987