LeetCode Blog

Solutions for LeetCode problems - Written by ansidev

3. Longest Substring Without Repeating Characters

Author's avatar
ansidev Posted on October 31, 2022

Problem

Given a string s, find the length of the longest substring without repeating characters.

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Constraints:

Analysis

AbbreviationStands for
CSWRCcurrent substring without repeating characters
LSWRClongest substring without repeating characters

Approaches

Approach 1

Approach

Solutions

func lengthOfLongestSubstring(s string) int {
	l := len(s)
	if l == 0 || l == 1 {
		return l
	}

	result, left := 1, 0
	lastIndex := map[byte]int{}
	lastIndex[s[0]] = 0
	for right := 1; right < l; right++ {
		if v, ok := lastIndex[s[right]]; ok {
			if left < v+1 {
				left = v + 1
			}
		}
		lastIndex[s[right]] = right
		if result < right-left+1 {
			result = right - left + 1
		}
	}

	return result
}

Complexity