I am trying to solve the problem of finding the longest substring without a repeating character from a given string.
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
start = 0
mlen = -1
cur_ = {}
cur = 0
while(start<len(s) and cur<len(s)):
if s[cur] in cur_ and cur_[s[cur]] >= start:
if cur - start > mlen:
mlen = cur - start
start = cur_[s[cur]] + 1
cur_[s[cur]] = cur
else:
cur_[s[cur]] = cur
if cur - start > mlen:
mlen = cur - start
cur = cur + 1
return mlen
x = Solution()
print(x.lengthOfLongestSubstring("abababcdef"))
I think I am solving it correctly:
Start a new substring when you encounter a repeated character.
But I am not getting the answers right?
In the above example the output is 5 whereas the correct answer is 6.
But for this case:
print(x.lengthOfLongestSubstring("ababa"))
the output is correct i.e. 2.
Not sure why am I failing that case? Thanks.