题解 | #牛群名字覆盖#
牛群名字覆盖
https://www.nowcoder.com/practice/e6cef4702e7841f59cf47daf9bafb241
- 题目考察的知识点 : 滑动窗口
- 题目解答方法的文字分析:
- 定义一个指针left来表示当前窗口的左端点,然后从左往右遍历整个字符串,可以使用哈希表need来记录指定英文字母出现的次数,使用哈希表cnt来记录窗口内各个字符出现的次数依次将每个字符加入窗口中:
- 如果当前窗口包含了所有指定英文字母,则更新答案并尝试将窗口左端点向右移动;
- 重复以上步骤 直到窗口不能再向右移动。
- 本题解析所用的编程语言: Python
- 完整且正确的编程代码
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param s string字符串 # @param t string字符串 # @return string字符串 # import collections class Solution: def minWindow(self , s: str, t: str) -> str: need = collections.Counter(t) cnt = {c: 0 for c in need} left, right = 0, 0 res = "" while right < len(s): if s[right] in cnt: cnt[s[right]] += 1 while all(cnt[c] >= need[c] for c in need): if not res or right - left + 1 < len(res): res = s[left:right+1] if s[left] in cnt: cnt[s[left]] -= 1 left += 1 right += 1 return res
牛客高频top202题解系列 文章被收录于专栏
记录刷牛客高频202题的解法思路