Python 解leetcode:3. Longest Substring Without Repeating Characters

  • 题目描述:求一个字符串的不含重复字符的最长连续子串的长度;

  • 思路:

  1. 使用一个哈希表保存字符出现的位置;
  2. 使用left和right分别表示子串的最左和最右字符的下标;
  3. 遍历字符串,如果当前字符在哈希表中并且当前字符在哈希中的位置大于left,表明left和right之间存在和right索引上相同的字符,此时把left置为当前值在哈希表中的值;
  4. 把当前索引值+1,表示是第几个字符,求出当前最大长度;
  5. 3-4步重复,直到获得遍历完成;

感觉这是个动态规划题,暂时没用动态规划分析,后续再说。

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        hashes = {}
        left, right, length = 0, 0, len(s)
        max_len = 0
        while right < length:
            if hashes.get(s[right]) and hashes[s[right]] >= left:
                left = hashes[s[right]]
            hashes[s[right]] = right + 1
            max_len = max(max_len, right - left + 1)
            right += 1
        return max_len