Sobes.tech
Middle+

// Дана строка s. Нужно найти длину самой длинной подстроки без повторяющихся символов. // Примеры: // s = "abcabcbb", ответ: 3 ("abc") // s = "cccccccc", ответ: 1 ("c") // s = "pwwkew", ответ: 3 ("wke") // s = "", ответ: 1 = 0 // Строка s состоит из английских букв, цифр, символов и пробелов func lengthOfLongestSubstring(s string) int { return 0 }

sobes.tech AI

Answer from AI

To find the length of the longest substring without repeating characters, you can use the "sliding window" algorithm with two pointers and a hash table to track the last positions of characters.

Example solution in Go:

def lengthOfLongestSubstring(s string) int {
    lastIndex := make(map[rune]int)
    maxLen := 0
    start := 0

    for i, ch := range s {
        if pos, found := lastIndex[ch]; found && pos >= start {
            start = pos + 1
        }
        lastIndex[ch] = i
        if currentLen := i - start + 1; currentLen > maxLen {
            maxLen = currentLen
        }
    }

    return maxLen
}

Explanation:

  • lastIndex stores the last index of each character.
  • start is the beginning of the current window without duplicates.
  • When a repeated character with index >= start is encountered, move start.
  • Update the maximum window length.

This algorithm runs in O(n) time, where n is the length of the string.

// Дана строка s. Нужно найти длину самой длинной… - sobes.tech