文章目录
寻找不含有重复字符的子串
lastOccurred[x]记录上次遇到x字符的位置,start表示此次子字符串开始位置。
1.对于每一个字母x,如果lastOccurred[x]不存在,或者小于start,则无需操作;
2.如果lastOccured[x]>=start,需要更新start为lastOccured[x]后一个位置。
3.最后更新lastOccured[x],更新maxLength。
实现
func searchsubStr(s string) int{
lastOccured := make(map[byte]int)
start :=0
maxLength :=0
for i,ch := range []byte(s){
lastI,ok := lastOccured [ch] //字符有可能从未匹配到
if ok & lastI >= start {
start = lastI + 1
}
if i - start + 1 > maxLength{ //如果此次变量的长度大于以前变量过的长度,更新最大长度。
maxLength = i - start +1
}
lastOccured[ch] = i
}
return maxLength
}