write a python code to return the length of longest non repeating substring in a string
- User
write a python code to return the length of longest non repeating substring in a string
- Assistant
To find the length of the longest non-repeating substring in a given string, you can use a sliding window approach. Here is a Python code example that implements this strategy:
def length_of_longest_substring(s: str) -> int: # Dictionary to store the last positions of each character. char_index_map = {} # Start of the current substring. start = 0 # The length of the longest substring. max_length = 0 for i, char in enumerate(s): # If the character is already in the map and its last occurrence is not before the # current substring's start, update the start position. if char in char_index_map and char_index_map[char] >= start: start = char_index_map[char] + 1 char_index_map[char] = i # Update the max_length if the current substring is longer. max_length = max(max_length, i - start + 1) return max_length # Test the function s = "abcabcbb" print(length_of_longest_substring(s)) # Expected output: 3