Longest Substring Without Repeating Characters

Intuition

The intuition behind the 3 solutions is to iteratively find the longest substring without repeating characters by maintaining a sliding window approach. We use two pointers (left and right) to represent the boundaries of the current substring. As we iterate through the string, we update the pointers and adjust the window to accommodate new unique characters and eliminate repeating characters.

Approach

  1. We use a set (charSet) to keep track of unique characters in the current substring.
  2. We maintain two pointers, left and right, to represent the boundaries of the current substring.
  3. The maxLength variable keeps track of the length of the longest substring encountered so far.
  4. We iterate through the string using the right pointer.
  5. If the current character is not in the set (charSet), it means we have a new unique character.
  6. We insert the character into the set and update the maxLength if necessary.
  7. If the character is already present in the set, it indicates a repeating character within the current substring.
  8. In this case, we move the left pointer forward, removing characters from the set until the repeating character is no longer present.
  9. We insert the current character into the set and continue the iteration.
  10. Finally, we return the maxLength as the length of the longest substring without repeating characters.

Complexity

  • Time complexity:
  • O(n)
  • Space complexity:
  • O(n)

Code

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        n = len(s)
        maxLength = 0
        charSet = set()
        left = 0
        
        for right in range(n):
            if s[right] not in charSet:
                charSet.add(s[right])
                maxLength = max(maxLength, right - left + 1)
            else:
                while s[right] in charSet:
                    charSet.remove(s[left])
                    left += 1
                charSet.add(s[right])
        
        return maxLength
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值