[python]leetcode(76). Minimum Window Substring

problem

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

solution

class Solution(object):
    def minWindow(self, s, t):

        from collections import defaultdict
        begin, end = 0, 0
        head, length = 0, float('inf')
        counter = len(t)
        d = defaultdict(int)
        for i in t:
            d[i] += 1

        while end < len(s):
            if d[s[end]] > 0:
                counter -= 1
            d[s[end]] -= 1    
            end += 1

            while counter == 0:
                if end - begin < length:
                    head = begin
                    length = end - begin
                if d[s[begin]] == 0:
                    #只有在t中出现的字符才会等于零
                    counter += 1
                d[s[begin]] += 1
                begin += 1


        return '' if length == float('inf') else s[head:head+length]

模板

当给定一个字符串让我们去找它的符合某些条件的子串时,通常使用哈希表和两个指针(滑动窗口),来解决问题。

int findSubstring(string s){
        vector<int> map(128,0);
        int counter; // check whether the substring is valid
        int begin=0, end=0; //two pointers, one point to tail and one  head
        int d; //the length of substring

        for() { /* initialize the hash map here */ }

        while(end<s.size()){

            if(map[s[end++]]-- ?){  /* modify counter here */ }

            while(/* counter condition */){ 

                 /* update d here if finding minimum*/

                //increase begin to make it invalid/valid again

                if(map[s[begin++]]++ ?){ /*modify counter here*/ }
            }  

            /* update d here if finding maximum*/
        }
        return d;
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值