Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add algorithm to get the length of the longest substring without repe… #10460

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
57 changes: 57 additions & 0 deletions strings/longest_substring_without_repeating_characters.py
@@ -0,0 +1,57 @@
"""
Longest substring without repeating characters Problem Statement: Given a string,
find the length of longest substring without repeating characters.
Example: The longest substring without repeating characters in the string
"abcabcbb" is "abc". Therefore, algorithm should return 3 as the output.
"""


def longest_substring_without_repeating_characters(string: str) -> int:
"""
Finds the length of longest substring without repeating characters.
>>> longest_substring_without_repeating_characters("abcabcbb")
3
>>> longest_substring_without_repeating_characters("bbbbb")
1
>>> longest_substring_without_repeating_characters("pwwkew")
3
>>> longest_substring_without_repeating_characters("")
0
>>> longest_substring_without_repeating_characters("a")
1
>>> longest_substring_without_repeating_characters("heaesgliengs")
6
>>> longest_substring_without_repeating_characters("general kenobi")
10
>>> longest_substring_without_repeating_characters("that's what she said")
7
>>> longest_substring_without_repeating_characters(69)
Traceback (most recent call last):
...
ValueError: longest_substring_without_repeating_characters() takes a string as input
"""

if not isinstance(string, str):
raise ValueError(
"longest_substring_without_repeating_characters() takes a string as input"
)

char_set: set[str] = set()
start = 0
max_length = 0

for end in range(len(string)):
while string[end] in char_set:
char_set.remove(string[start])
start += 1
char_set.add(string[end])
if max_length < end - start + 1:
max_length = end - start + 1

return max_length


if __name__ == "__main__":
import doctest

doctest.testmod()