题解 | #最长不含重复字符的子字符串#

最长不含重复字符的子字符串

https://www.nowcoder.com/practice/48d2ff79b8564c40a50fa79f9d5fa9c7

package main

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 滑动窗口
 * @param s string字符串
 * @return int整型
 */
func lengthOfLongestSubstring(s string) int {
	// write code here
	if len(s) == 0 {
		return 0
	}

	charIndex := make(map[byte]int)
	maxLen, start := 0, 0

	for i := range s {
		char := s[i]
		if idx, found := charIndex[char]; found && idx >= start {
			// 当前字符如果出现过,并且它的上一次出现位置在当前起点之后
			start = idx + 1
		}
		// 更新字符的最新位置
		charIndex[char] = i

		// 更新最大长度
		if i-start+1 > maxLen {
			maxLen = i - start + 1
		}
	}

	return maxLen
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务