3. Longest Substring Without Repeating Characters

Problem


Tags: Hash Table, String, Sliding Window

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:

  • 0 <= s.length <= 5 * 10^4
  • s consists of English letters, digits, symbols and spaces.

Code

GO

// 3. Longest Substring Without Repeating Characters (1/19/53372)
// Runtime: 8 ms (67.23%) Memory: 2.82 MB (64.24%) 

func lengthOfLongestSubstring(s string) int {
	solution := 0

	dict := make(map[byte]int)

	front, back := 0, 0
	for front = 0; front < len(s); front++ {
		if pos, exists := dict[s[front]]; exists {
			for back <= pos {
				delete(dict, s[back])
				back++
			}
		} else if front-back+1 > solution {
			solution = front - back + 1
		}
		dict[s[front]] = front
	}

	return solution
}

JS

// 3. Longest Substring Without Repeating Characters (2/16/53726)
// Runtime: 88 ms (86.92%) Memory: 43.28 MB (94.98%) 

/**
 * @param {string} s
 * @return {number}
 */
function lengthOfLongestSubstring(s) {
    let start = 0,
        end = 0,
        max = 0;
    const set = new Set();
    while (end < s.length) {
        if (!set.has(s[end])) {
            set.add(s[end++]);
            max = Math.max(max, set.size);
        } else set.delete(s[start++]);
    }
    return max;
}