Leetcode Tag Search | Back

3. Longest Substring Without Repeating Characters

Category: /leetcode

Leetcode Link | Sliding window template

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.

Solution:

  • Sliding window
def lengthOfLongestSubstring(self, s: str) -> int:
  if not s: return 0 

  window = {}
  l, r = 0, 0
  res = 0
  while r < len(s):
    ch = s[r]
    window[ch] = window.get(ch, 0) + 1 
    r += 1

    while window[ch] > 1:
      l_ch = s[l]
      window[l_ch] -= 1
      l += 1
    res = max(r - l, res)
  return res

讨论

提示

  • 如果看不到讨论部分, 请暂时关掉adblock in Firefox/Chrome
  • 本网站使用Javascript实现评论功能, 此处外链对提高您的网站PR没有帮助. (潜台词: 请不要灌水, 谢谢)