Skip to content

Commit 61fada7

Browse files
refactor(strings, longest_self_contained_substring): add type hints
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
1 parent a3d3e16 commit 61fada7

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

pystrings/longest_self_contained_substring/__init__.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -52,24 +52,33 @@ def longest_self_contained_substring(s: str) -> int:
5252
return max_length
5353

5454

55-
def max_substring_length(s):
55+
def max_substring_length(s: str) -> int:
5656
"""
5757
Finds the length of the longest substring of s that is self-contained.
5858
5959
A self-contained substring is one in which all characters only appear within the substring.
6060
61-
The function works by iterating over all possible substrings of s and checking if each one is self-contained.
62-
63-
It does this by keeping track of the first and last occurrence of each character in s. It then checks if each
64-
character in a substring appears outside of the substring's range. If it does, the substring is not self-contained.
65-
66-
Finally, it returns the length of the longest self-contained substring it found.
61+
The function uses an optimized window expansion approach. For each unique character as a starting point,
62+
it defines an initial window from the character's first to last occurrence. The window is expanded to include
63+
all occurrences of characters within it, and is invalidated if any character's first occurrence lies before
64+
the window start.
6765
6866
Parameters:
6967
s (str): The string to find the longest self-contained substring of
7068
7169
Returns:
7270
int: The length of the longest self-contained substring of s
71+
72+
Examples:
73+
>>> max_substring_length("xyyx")
74+
2
75+
>>> max_substring_length("xyxy")
76+
-1
77+
>>> max_substring_length("abacd")
78+
4
79+
80+
Note:
81+
Time complexity: O(n), Space complexity: O(1) for fixed character set size.
7382
"""
7483
first = {}
7584
last = {}

0 commit comments

Comments
 (0)