Longest Substring Without Repeating CharactersGiven a string s find the length of the longest substring without repeating characters.
Question
Longest Substring Without Repeating Characters
Given a string s
, find the length of the longest substring without repeating characters.
Solution
This problem can be solved using the sliding window technique. Here are the steps in Python:
-
Initialize two pointers,
start
andend
, to point to the beginning of the string. These pointers will define our current substring. -
Initialize a dictionary,
used_chars
, to keep track of the characters we have seen and their latest positions. -
While
end
is less than the length of the string, do the following:-
If the character at
end
is not inused_chars
, add it toused_chars
and incrementend
. -
If the character at
end
is inused_chars
, movestart
to the right of the previous instance of the character atend
and update its position inused_chars
.
-
-
The length of the longest substring without repeating characters is the maximum length of the substring we have seen during this process.
Here is the Python code for the above steps:
def lengthOfLongestSubstring(s):
start = max_length = 0
used_chars = {}
for i, char in enumerate(s):
if char in used_chars and start <= used_chars[char]:
start = used_chars[char] + 1
else:
max_length = max(max_length, i - start + 1)
used_chars[char] = i
return max_length
This function works by keeping track of the longest substring seen so far and the start of the current substring. When it sees a repeating character, it moves the start of the current substring to the right of the previous instance of the repeating character and updates the position of the repeating character. The length of the longest substring is updated whenever a longer substring is found.
Similar Questions
Given a string consisting of opening and closing parenthesis (let moonparenthesis only), find the length of the longest valid parenthesis sub-string
Length of the longest wordWrite a Python program to read a list of words and return the length of the longest word present within the list elements
Write a Java program to check whether a substring(abc) appears before a period(.) within a given string
Given a string A and two integer B and C.Find and return the substring of A starting from index B and ending with index C.
The library function used to find the last occurrence of a character in a string is
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.