To solve this problem, we need to find the length of the longest substring without repeating characters in a given string. The optimal approach to this problem is using the sliding window technique, which efficiently tracks the current substring and adjusts its boundaries to avoid duplicates.
The sliding window technique uses two pointers (left and right) to represent the current window of the substring we are checking. We also use a set to keep track of characters in the current window to quickly detect duplicates:
left pointer at 0, max_len to store the length of the longest substring found, and an empty set char_set to track characters in the current window.right pointer. For each character:
char_set, move the left pointer to the right, removing characters from char_set until the duplicate character is removed.char_set.max_len if the current window size (from left to right) is larger than the current max_len.max_len will be the length of the longest substring without repeating characters.def length_of_longest_substring(s: str) -> int:
char_set = set()
left = 0
max_len = 0
for right in range(len(s)):
while s[right] in char_set:
char_set.remove(s[left])
left += 1
char_set.add(s[right])
current_len = right - left + 1
if current_len > max_len:
max_len = current_len
return max_len
# Example usage and test cases
if __name__ == "__main__":
test_cases = [
("abcabcbb", 3),
("bbbbb", 1),
("pwwkew", 3),
("", 0),
("a", 1),
("au", 2)
]
for s, expected in test_cases:
result = length_of_longest_substring(s)
assert result == expected, f"Test case failed: Input {s} → Expected {expected}, Got {result}"
print("All test cases passed successfully!")
This approach efficiently handles all edge cases, including empty strings, strings with all unique characters, and strings with repeated characters. The test cases confirm the correctness of the solution.
(免責(zé)聲明:本文為本網(wǎng)站出于傳播商業(yè)信息之目的進(jìn)行轉(zhuǎn)載發(fā)布,不代表本網(wǎng)站的觀點(diǎn)及立場。本文所涉文、圖、音視頻等資料的一切權(quán)利和法律責(zé)任歸材料提供方所有和承擔(dān)。本網(wǎng)站對此資訊文字、圖片等所有信息的真實(shí)性不作任何保證或承諾,亦不構(gòu)成任何購買、投資等建議,據(jù)此操作者風(fēng)險(xiǎn)自擔(dān)。) 本文為轉(zhuǎn)載內(nèi)容,授權(quán)事宜請聯(lián)系原著作權(quán)人,如有侵權(quán),請聯(lián)系本網(wǎng)進(jìn)行刪除。