【Leetcode-3】
一、题目:无重复字符的最长子串
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
二、代码
def lengthOfLongestSubstring(self, s: str) -> int: from collections import defaultdict look_up = defaultdict(int) i = j = window = max_val = 0 while j <= len(s) - 1: if look_up[s[j]] > 0: window += 1 look_up[s[j]] += 1 j += 1 while window > 0: if look_up[s[i]] > 1: window -= 1 look_up[s[i]] -= 1 i += 1 max_val = max(max_val, j - i) return max_val
【Leetcode-340】
一、题目:至多包含k个不同字符的最长子串
给定一个字符串 s ,找出 至多 包含 k 个不同字符的最长子串 T。
二、代码:
def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int: from collections import defaultdict lookup = defaultdict(int) start = 0 end = 0 max_len = 0 counter = 0 while end < len(s): if lookup[s[end]] == 0: counter += 1 lookup[s[end]] += 1 end += 1 while counter > k: if lookup[s[start]] == 1: counter -= 1 lookup[s[start]] -= 1 start += 1 max_len = max(max_len, end - start) return max_len
【Leetcode-76】最小覆盖子串
一、题目:
给你一个字符串 s
、一个字符串 t
。返回 s
中涵盖 t
所有字符的最小子串。如果 s
中不存在涵盖 t
所有字符的子串,则返回空字符串 ""
。
二、代码:
def minWindow(self, s: ‘str‘, t: ‘str‘) -> ‘str‘: from collections import defaultdict lookup = defaultdict(int) for c in t: lookup[c] += 1 start = 0 end = 0 min_len = float("inf") counter = len(t) res = "" while end < len(s): if lookup[s[end]] > 0: counter -= 1 lookup[s[end]] -= 1 end += 1 while counter == 0: if min_len > end - start: min_len = end - start res = s[start:end] if lookup[s[start]] == 0: counter += 1 lookup[s[start]] += 1 start += 1 return res
原文:https://www.cnblogs.com/EstherLjy/p/14607951.html