Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) < 1:
return 0
hmap = {}
longest = 0
left = -1
right = 0
while right < len(s):
if s[right] in hmap:
d = right - left - 1
if longest < d:
longest = d
if hmap[s[right]] > left:
left = hmap[s[right]]
hmap[s[right]] = right
right += 1
# end of string
d = right - left - 1
if longest < d:
longest = d
return longest
v2, nice and clean
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
hmap = {}
left = 0
longest = 0
for right in xrange(len(s)):
if s[right] in hmap:
left = max(left, hmap[s[right]]+1)
hmap[s[right]] = right
longest = max(longest, right - left + 1)
return longest
留言列表