Skip to content

Commit

Permalink
Update minimum-window-substring.py
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 committed May 20, 2016
1 parent 26adcfb commit 2d42da9
Showing 1 changed file with 24 additions and 17 deletions.
41 changes: 24 additions & 17 deletions Python/minimum-window-substring.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,44 @@
# Time: O(n)
# Space: O(k), k is the number of different characters
#
# 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).

# 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).
#
# For example,
# S = "ADOBECODEBANC"
# T = "ABC"
# Minimum window is "BANC".
#
# Note:
# If there is no such window in S that covers all characters in T, return the emtpy string "".
# If there is no such window in S that covers all characters in T,
# return the emtpy string "".
#
# If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
#
# If there are multiple such windows, you are guaranteed that
# there will always be only one unique minimum window in S.

class Solution:
# @return a string
def minWindow(self, S, T):
class Solution(object):
def minWindow(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
current_count = [0 for i in xrange(52)]
expected_count = [0 for i in xrange(52)]

for char in T:
for char in t:
expected_count[ord(char) - ord('a')] += 1

i, count, start, min_width, min_start = 0, 0, 0, float("inf"), 0
while i < len(S):
current_count[ord(S[i]) - ord('a')] += 1
if current_count[ord(S[i]) - ord('a')] <= expected_count[ord(S[i]) - ord('a')]:
while i < len(s):
current_count[ord(s[i]) - ord('a')] += 1
if current_count[ord(s[i]) - ord('a')] <= expected_count[ord(s[i]) - ord('a')]:
count += 1

if count == len(T):
while expected_count[ord(S[start]) - ord('a')] == 0 or\
current_count[ord(S[start]) - ord('a')] > expected_count[ord(S[start]) - ord('a')]:
current_count[ord(S[start]) - ord('a')] -= 1
if count == len(t):
while expected_count[ord(s[start]) - ord('a')] == 0 or\
current_count[ord(s[start]) - ord('a')] > expected_count[ord(s[start]) - ord('a')]:
current_count[ord(s[start]) - ord('a')] -= 1
start += 1

if min_width > i - start + 1:
Expand All @@ -43,7 +49,8 @@ def minWindow(self, S, T):
if min_width == float("inf"):
return ""

return S[min_start:min_start + min_width]
return s[min_start:min_start + min_width]


if __name__ == "__main__":
print Solution().minWindow("ADOBECODEBANC", "ABC")

0 comments on commit 2d42da9

Please sign in to comment.