From 6c1f592eae3d76ac9410b6599a89357ade5f1365 Mon Sep 17 00:00:00 2001 From: leonardchinonso <36096513+leonardchinonso@users.noreply.github.com> Date: Sat, 17 Apr 2021 00:22:22 +0100 Subject: [PATCH] Alternative Solution --- 1-100q/03.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/1-100q/03.py b/1-100q/03.py index 73f2c4d..09bc929 100644 --- a/1-100q/03.py +++ b/1-100q/03.py @@ -25,4 +25,29 @@ def lengthOfLongestSubstring(self, s): result = max(result, end-start+1) mapSet[s[end]] = end+1 - return result \ No newline at end of file + return result + + +''' +Alternative solution +''' + +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + if len(s) <= 1: + return len(s) + + _set = set() + ans = 0 + i, j = 0, 0 + + while j < len(s): + if s[j] not in _set: + _set.add(s[j]) + j += 1 + ans = max(ans, len(_set)) + else: + _set.remove(s[i]) + i += 1 + + return ans