Created
October 14, 2017 21:53
-
-
Save cixuuz/bcd77f89f094307e435d81f609d2226e to your computer and use it in GitHub Desktop.
[76. Minimum Window Substring] #leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution(object): | |
# O(n) O(n) | |
def minWindow(self, s, t): | |
# get counts of each character and length of t | |
need, missing = collections.Counter(t), len(t) | |
# initialize indice | |
i = I = J = 0 | |
# loop s | |
for j, c in enumerate(s, 1): | |
# make sure only needed is reduced | |
missing -= need[c] > 0 | |
# minus the count for every char | |
need[c] -= 1 | |
if not missing: | |
# missing is zero | |
# left move to one of needed chars | |
while i < j and need[s[i]] < 0: | |
need[s[i]] += 1 | |
i += 1 | |
# find min length | |
if not J or j - i <= J - I: | |
I, J = i, j | |
# return result | |
return s[I:J] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment