北美程序员面试干货

LeetCode 340 [Longest Substring

2016-08-08  本文已影响242人  Jason_Yuan

原题

给定一个字符串,找到最多有k个不同字符的最长子字符串。

样例
例如,给定 s = "eceba" , k = 3,
T 是 "eceb",长度为 4.

解题思路

完整代码

class Solution:
    # @param s : A string
    # @return : An integer
    def lengthOfLongestSubstringKDistinct(self, s, k):
        # write your code here
        if not s or not k:
            return 0
        if len(s) < k:
            return len(s)
        right, length = 0, 0
        sourceHash = {}
        for left in range(len(s)):
            while len(sourceHash) <= k and right < len(s):
                if s[right] not in sourceHash:
                    sourceHash[s[right]] = 1
                else:
                    sourceHash[s[right]] += 1
                right += 1
            if len(sourceHash) == k + 1 and right - left - 1 > length:
                length = right - left - 1
            elif right >= len(s) and right - left > length:
                length = right - left
                
            sourceHash[s[left]] -= 1
            if sourceHash[s[left]] == 0:
                del sourceHash[s[left]]
        
        return length
上一篇 下一篇

猜你喜欢

热点阅读