Middle+
// Дана строка s. Нужно найти длину самой длинной подстроки без повторяющихся символов. // Примеры: // s = "abcabcbb", ответ: 3 ("abc") // s = "cccccccc", ответ: 1 ("c") // s = "pwwkew", ответ: 3 ("wke") // s = "", ответ: 1 ("") // Строка s состоит из английских букв, цифр, символов и пробелов func lengthOfLongestSubstring(s string) int { return 0 }
sobes.tech AI
Answer from AI
To solve the problem of finding the length of the longest substring without repeating characters, you can use the "sliding window" algorithm. The idea is to maintain two pointers that define the current substring without repeats, and update the maximum length as you move forward.
Example implementation in Go:
func lengthOfLongestSubstring(s string) int {
charIndex := make(map[rune]int) // stores the last index of each character
maxLen := 0
start := 0
for i, ch := range s {
if lastPos, found := charIndex[ch]; found && lastPos >= start {
start = lastPos + 1
}
charIndex[ch] = i
if i - start + 1 > maxLen {
maxLen = i - start + 1
}
}
return maxLen
}
Explanation:
startis the beginning of the current window without repeating characters.charIndexstores the last index of each character.- If a repeated character is found within the current window, move
startto one position after the last occurrence of that character. - Update the maximum length at each step.
This algorithm runs in O(n) time, where n is the length of the string.