Reputation: 19
Could you please tell what is wrong with my code? I am trying to solve the following problem: "Given a string s, find the length of the longest substring without repeating characters."
Example:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc"
, with the length of 3.
My code is as follows:
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
count=[0]*len(s);
for i in range(0,len(s)):
for j in range(1,len(s)-i):
if s[i]!=s[i+j]:
count[i]=count[i]+1;
else:
break;
return max(count);
It returns 4, although the answer is 3.
Upvotes: 2
Views: 76
Reputation: 522
here you go, start at 1 because every letter is technically a unique string of len 1, and each loop checks if the next letter in in the slice currently looked at
def lengthOfLongestSubstring(s: str) -> int:
if s=='': return 0
count=[1]*len(s)
for i in range(0,len(s)-1):
for j in range(i+1,len(s)):
if s[j] in s[i:j]:
break
count[i]+=1
return max(count)
Upvotes: 2