close

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

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 g0d2 的頭像
    g0d2

    kazi1@的部落格

    g0d2 發表在 痞客邦 留言(0) 人氣()