classSolution(object): deflengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ dic = {} res = 0 start = 0 for i in range(len(s)): if s[i] in dic and start <= dic[s[i]]: start = dic[s[i]] + 1 else: res = max(res, i - start + 1) dic[s[i]] = i return res
159. Longest Substring with At Most Two Distinct Characters.
340. Longest Substring with At Most K Distinct Characters.
classSolution(object): deflengthOfLongestSubstringTwoDistinct(self, s): """ :type s: str :rtype: int """ char_dict = {} start = 0 res = 0 for i in range(len(s)): if s[i] notin char_dict: char_dict[s[i]] = 1 else: char_dict[s[i]] += 1
while len(char_dict)>2: temp = s[start] if char_dict[temp] > 1: char_dict[temp] -= 1 else: del(char_dict[temp]) start += 1 res = max(res, i -start + 1) return res
另外的形式
395. Longest Substring with At Least K Repeating Characters
At least就表明至少有那么多,用字典就不太好使了,因为要不断考虑到之前的情况,倒不如退而求其次,divide and conquer 找到最不可能的字符,然后知道里面的字符至少出现过k次
1 2 3 4 5 6
if len(s) < k: return0 c = min(set(s), key=s.count) ## 按照count排序 if s.count(c) >= k: return len(s) ## 都满足 return max(self.longestSubstring(t, k) for t in s.split(c))