File tree Expand file tree Collapse file tree 1 file changed +16
-7
lines changed
pystrings/longest_self_contained_substring Expand file tree Collapse file tree 1 file changed +16
-7
lines changed Original file line number Diff line number Diff 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 = {}
You can’t perform that action at this time.
0 commit comments