Given a string s
, find the length of the longest substring without repeating characters.
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if not s or len(s)==1:
return len(s)
substring=""
longest=""
for i in range(0,len(s)):
if s[i] not in substring:
substring+=s[i]
if len(substring)>len(longest):
longest=substring
elif substring[-1]==s[i]:
substring=s[i]
else:
substring=substring[substring.index(s[i])+1:]+s[i]
return len(longest)
Time Complexity: O(n)
The worst case is going all through each character of the string s
.
Space Complexity: O(1)
In the worst case we would have to store all n characters of the string s in hashmap, but this is a constant value which at max can go up to O(62) as explained in solution 1.
I realized that my solution is similar to the "Sliding Window" Method, and there is a lot of parts to be improved.
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
max_len = start = 0
for i in range(len(s)):
if s[i] not in s[start:i]:
max_len = max(max_len, i+1-start)
else:
start+=(1+s[start:i].index(s[i]))
return(max(max_len, len(s)-start))
This solutions is a better approch because
1. It covers the both ways to repeate the charater which I handled them differently.
2. It doesn't use memory for saving the substring and the longest substring.
References
https://leetcode.com/problems/longest-substring-without-repeating-characters/
https://www.code-recipe.com/post/longest-substring-without-repeating-characters
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1843466/Python-sliding-window-faster-than-90