1. 程式人生 > >76.視窗滑動最小子串

76.視窗滑動最小子串

Minimum Window Substring

問題描述:

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".

參考答案(c++):

class Solution {
public:
    string minWindow(string s, string
t) { vector<int> map(128,0); for(auto c: t) map[c]++; int counter=t.size(), begin=0, end=0, d=INT_MAX, head=0; while(end<s.size()){ if(map[s[end++]]-->0) counter--; //in t while(counter==0){ //valid if(end-begin<d) d=end-(head=begin); if
(map[s[begin++]]++==0) counter++; //make it invalid } } return d==INT_MAX? "":s.substr(head, d); } };

效能:

這裡寫圖片描述

參考答案(python):

class Solution(object):
    def minWindow(self, s, t):
        need, missing = collections.Counter(t), len(t)
        i = I = J = 0
        for
j, c in enumerate(s, 1): missing -= need[c] > 0 need[c] -= 1 if not missing: while i < j and need[s[i]] < 0: need[s[i]] += 1 i += 1 if not J or j - i <= J - I: I, J = i, j return s[I:J]

效能:

這裡寫圖片描述