内容中心

2026年评价高的沧州重型输送机滚筒横向对比厂家推荐-沧州路博机械制造有限公司

To solve this problem, we need to find the length of the longest substring without repeating characters in a given string. The optimal approach involves using a sliding window technique combined with a data structure to track the last occurrence of each character, ensuring an efficient solution with linear time complexity.

Approach

The sliding window technique uses two pointers (left and right) to represent the current substring being evaluated. We also maintain a data structure to keep track of the last index of each character encountered. Here's the detailed breakdown:

  1. Initialization:

    • A list last_occurrence (size 128 for ASCII characters) to store the last index of each character.
    • left pointer starts at 0 (beginning of the string).
    • max_len to keep track of the length of the longest substring found.
  2. Iterate with right pointer:

    • For each character at position right, check if it has been seen before and if its last occurrence is within the current window (i.e., >= left).
    • If it has, move the left pointer to the position right after the last occurrence of the current character to exclude the duplicate.
    • Update the last_occurrence of the current character to right.
    • Calculate the length of the current window (right - left +1) and update max_len if this length is greater than the current max_len.

This approach ensures that each character is processed exactly once, leading to an O(n) time complexity, where n is the length of the string. The space complexity is O(1) since the size of last_occurrence is fixed (128 characters).

Solution Code

def lengthOfLongestSubstring(s: str) -> int:
    last_occurrence = [-1] * 128  # Covers all ASCII characters
    left = 0
    max_len = 0

    for right in range(len(s)):
        char_code = ord(s[right])
        if last_occurrence[char_code] >= left:
            left = last_occurrence[char_code] + 1
        last_occurrence[char_code] = right
        max_len = max(max_len, right - left + 1)

    return max_len

Explanation

  • Sliding Window: The window is defined by left and right pointers. As right moves forward, we expand the window. If a duplicate is found within the window, left moves to shrink the window to exclude the duplicate.
  • Last Occurrence Tracking: The last_occurrence list allows us to quickly check if a character has been seen and where it was last seen, which helps in adjusting the window efficiently.
  • Efficiency: This method runs in O(n) time because each character is processed once, and each pointer (left and right) moves forward only, never backward. The space used is constant (O(1)) since the list size is fixed.

This solution efficiently handles all edge cases, including empty strings, single characters, and strings with all unique characters. It is optimal and widely used for this problem.

沧州路博机械制造有限公司

沧州路博机械制造有限公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?