Description
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
Example:
1 | Input: S = "ADOBECODEBANC", T = "ABC" |
Note:
- If there is no such window in S that covers all characters in T, return the empty string
""
. - If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
解法
因为时间复杂度限制在了O(n),因此只能通过至少一次遍历字符串实现,当时想到了应该利用哈希做题,具体思路为:用一个哈希表记录t中字符剩下的需要出现的次数(对于给定范围的字符串而言即s[start,i]),为负数时说明多出现了几次,用变量num记录给定范围字符串中还缺少多少个t中的字母,那么,当num为0时即找到一个符合条件的字符串。整体思路为先把所有的T中的字符找到,然后从左端缩减这个字符串,直到不能完全包含T,是一个经典的滑动窗口题
具体代码如下:
1 | class Solution { |