func lengthOfLongestSubstringTwoDistinct(s string) int {
if len(s) <= 2 {
return len(s)
}
leftIdx, maxLen := 0, 0
charIdxMap := make(map[uint8]int)
for i:=0; i<len(s); i++ {
// fmt.Println(" ---- ", i)
c := s[i]
if _, ok := charIdxMap[c]; !ok { //不存在
if len(charIdxMap) >=2 { // 达到2个,left需要滑动
leftCh := s[leftIdx]
leftIdx = charIdxMap[leftCh]
if leftIdx < i - 1{
leftIdx += 1
delete(charIdxMap, leftCh)
}else { // leftIdx == i-1
for k, idx := range charIdxMap {
if k != leftCh {
if leftIdx > idx + 1 {
leftIdx = idx + 1
}
delete(charIdxMap, k)
}
}
}
}
}
// update
charIdxMap[c] = i
if i-leftIdx+1 > maxLen {
maxLen = i-leftIdx+1
}
// fmt.Println(leftIdx, charIdxMap, s[leftIdx:i+1],maxLen)
}
return maxLen
}
作者:lambda01
链接:https://leetcode-cn.com/problems/longest-substring-with-at-most-two-distinct-characters/solution/golang-by-lambda01/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
有疑问加站长微信联系(非本文作者)