class Solution1(object):
def minWindow(self, s, t):
"""
use a dict to store the count of d each character of t, we use the value of dict to represent how many character current string surplus for t
if values less than 0, it's means the character is redundant, so we can jump it and add one to the value
use two pointer left and right to identify current string
we first scan from left to right and get index which s[:index+1] contains t
the move right pointer one step at a time, after that, we move left pointer, if dict[s[left]] < 0, we jump it until dict[s[left]] > 0
"""
from collections import defaultdict
dict_t = defaultdict(int)
for char in t:
dict_t[char] += 1
count = len(t)
index = 0
for i in range(len(s)):
if dict_t[s[i]] > 0:
dict_t[s[i]] -= 1
count -= 1
if count == 0:
index = i
break
else:
dict_t[s[i]] -= 1
if count > 0: return ""
left, right = 0, index
result = s[left: right+1]
while(True):
while(dict_t[s[left]] < 0):
dict_t[s[left]] += 1
left += 1
if len(result) > right - left + 1:
result = s[left:right+1]
right += 1
if right == len(s):
break
dict_t[s[right]] -= 1
return result
class Solution2(object):
"""
a little optimization of solution 1
we only need to store character appear in t
"""
def minWindow(self, s, t):
dict_t = {}
for char in t:
dict_t[char] = dict_t.get(char, 0) + 1
count = len(t)
index = -1
for i in range(len(s)):
if s[i] in dict_t:
if dict_t[s[i]] > 0:
count -= 1
dict_t[s[i]] -=1
if count == 0:
index = i
break
if count > 0: return ""
left, right, result = 0, index, s[0:index+1]
while(True):
while(s[left] not in dict_t or dict_t[s[left]] < 0):
if s[left] in dict_t:
dict_t[s[left]] += 1
left += 1
if len(result) > right - left + 1:
result = s[left:right+1]
right += 1
if right == len(s):
break
if s[right] in dict_t:
dict_t[s[right]] -= 1
return result
相关文章:
- Minimum Spanning Tree 2019-07-13
- Leetcode 5. Longest Palindromic Substring(最长回文子串, Manacher算法) 2019-08-26
- LeetCode 76,一题教会你面试算法时的思考套路 2020-06-10
- LeetCode 5271. 访问所有点的最小时间 Minimum Time Visiting All Points 2019-11-24
- Leetcode 931. Minimum falling path sum 最小下降路径和(动态规划) 2018-11-04
- 76、django之内置Admin 2017-12-13
- Leetcode之动态规划(DP)专题-详解983. 最低票价(Minimum Cost For Tickets) 2021-11-27
- 【深入浅出-JVM】(76):classloader 2019-09-16