From f52b64ba4f89a54ccd51ee37dbba4a84ae20feb7 Mon Sep 17 00:00:00 2001 From: Yigid BALABAN Date: Wed, 11 Sep 2024 20:30:45 +0300 Subject: [PATCH] it passed! (270ms, 16.58MB) --- ...-substring-without-repeating-characters.py | 32 +++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/longest-substring-without-repeating-characters.py b/longest-substring-without-repeating-characters.py index 12bc245..448c394 100644 --- a/longest-substring-without-repeating-characters.py +++ b/longest-substring-without-repeating-characters.py @@ -3,7 +3,8 @@ # neetcode 2024 # longest substring without repeating characters -def solution(s: str) -> int: +# my initial solution +def solution0(s: str) -> int: if len(s) <= 1: return len(s) @@ -25,6 +26,34 @@ def solution(s: str) -> int: return longest +# hint: sliding window +def solution(s: str) -> int: + if len(s) <= 1: + return len(s) + + longest = 0 + left = 0 + + def count(ss: str): + c = {} + for ch in ss: + if ch in c.keys(): + return None + c[ch] = 1 + return len(ss) + + for right in range(len(s)): + sample = s[left:right+1] + cs = count(sample) + if not cs: + left = left + 1 + right = left + else: + longest = cs + + return longest + + print(solution("") == 0) print(solution("a") == 1) print(solution("aaa") == 1) @@ -35,4 +64,3 @@ print(solution("abcccabcxyz") == 6) print(solution("axyzqaxyzqdf") == 7) print(solution("wsslpluuwekuaxt") == 7) print(solution("wwwwwwwwwsslpluuwekuaxt") == 7) -