LeetCode076 Minimum Window Substring

详细见:leetcode.com/problems/minimum-window-substring


Java Solution: github

package leetcode;

import java.util.HashMap;

/*
 * 	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 empty string "".
	
	If there are multiple such windows, you are guaranteed that 
	there will always be only one unique minimum window in S.
 */

public class P076_MinimumWindowSubstring {
	public static void main(String[] args) {
		System.out.println(new Solution2().minWindow("ADOBECODEBANC", "ABC"));
	}
	static class Solution {
		public String minWindow(String S, String T) {
	        HashMap<Character, Integer> dict = new HashMap<>();
	        for (int i = 0; i < T.length(); i++) {
	            char c = T.charAt(i);
	            if (!dict.containsKey(c))
	                dict.put(c, 1);
	            else
	                dict.put(c, dict.get(c) + 1);
	        }
	        HashMap<Character, Integer> found = new HashMap<>();
	        int foundCounter = 0;
	        int start = 0;
	        int end = 0;
	        int min = Integer.MAX_VALUE;
	        String minWindow = "";
	        while (end < S.length()) {
	            char c = S.charAt(end);
	            if (dict.containsKey(c)) {
	                if (found.containsKey(c)) {
	                    if (found.get(c) < dict.get(c))
	                        foundCounter++;
	                    found.put(c, found.get(c) + 1);
	                } else {
	                    found.put(c, 1);
	                    foundCounter++;
	                }
	            }
	            if (foundCounter == T.length()) {
	                char sc = S.charAt(start);
	                while (!found.containsKey(sc) || found.get(sc) > dict.get(sc)) {
	                    if (found.containsKey(sc) && found.get(sc) > dict.get(sc))
	                        found.put(sc, found.get(sc) - 1);
	                    start++;
	                    sc = S.charAt(start);
	                }
	                if (end - start + 1 < min) {
	                    minWindow = S.substring(start, end + 1);
	                    min = end - start + 1;
	                }
	            }
	            end++;
	        }
	        return minWindow;
	    }
	}
	/*
	 * 	AC
	 * 	82 ms
	 */
	static class Solution2 {
		public String minWindow(String S, String T) {
			String ans = "";
			HashMap<Character, Integer> target = new HashMap<Character, Integer>();
			HashMap<Character, Integer> current = new HashMap<Character, Integer>();
			int sti = 0, eni = 0, min = Integer.MAX_VALUE, cou = 0, lens = S.length(), lent = T.length();
			for (int i = lent - 1; i > -1; i --) {
				char tc = T.charAt(i);
				if (target.containsKey(tc)) {
					target.put(tc, target.get(tc) + 1);
				} else {
					target.put(tc, 1);
				}
			}
			while (eni < lens) {
				char sc = S.charAt(eni);
				if (target.containsKey(sc)) {
					if (current.containsKey(sc)) {
						if (current.get(sc) < target.get(sc))
							cou ++;
						current.put(sc, current.get(sc) + 1);
					} else {
						current.put(sc, 1);
						cou ++;
					}
				}
				if (cou == lent) {
					char s = S.charAt(sti);
					while (! current.containsKey(s) || current.get(s) > target.get(s)) {
						if (current.containsKey(s) && current.get(s) > target.get(s))
							current.put(s, current.get(s) - 1);
						s = S.charAt(++ sti);
					}
					if (eni - sti + 1 < min) {
						ans = S.substring(sti, eni + 1);
						min = eni - sti + 1;
					}
				}
				eni ++;
			}
			return ans;
		}
	}
}


C Solution: github

/*
    url: leetcode.com/problems/minimum-window-substring/
    AC 6ms 25.00%
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

char* minWindow(char* s, char* t) {
    int m[128], sn = strlen(s), tn = strlen(t);
    int cnt = tn, i = 0, j = 0, d = INT_MAX, h = 0;
    char *ans = NULL;
    for (i = 0; i < 128; i ++) m[i] = 0;
    for (i = 0; i < tn ;i ++) m[t[i]] ++;
    i = 0;
    while (j < sn) {
        if (m[s[j++]] -- > 0) cnt --;
        while (cnt == 0) {
            if (j-i < d) {
                d = j - i;
                h = i;
            }
            if (m[s[i++]]++ == 0) cnt ++;
        }
    }
    d = d == INT_MAX ? 0 : d;
    ans = (char*) malloc(sizeof(char) * (d+1));
    for (i = 0; i < d; i ++) ans[i] = s[i+h];
    ans[d] = '\0';
    return ans;
}

int main() {
    char* s = "cabwefgewcwaefgcf";
    char* t = "caz";
    char* ans = minWindow(s, t);
    printf("answer is %s\r\n", ans);
    free(ans);
    return 0;
}


Python Solution: github

#coding=utf-8

'''
    url: leetcode.com/problems/minimum-window-substring
    @author:     zxwtry
    @email:      zxwtry@qq.com
    @date:       2017年4月18日
    @details:    Solution: 152ms 77.17%
'''

class Solution(object):
    def minWindow(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        m, sn, tn = [0]*128, len(s), len(t)
        i, j, d, h = 0, 0, 1 << 30, 0
        cnt = tn
        for k in range(tn): m[ord(t[k])] += 1
        while j < sn:
            if m[ord(s[j])] > 0: cnt -= 1
            m[ord(s[j])] = m[ord(s[j])] - 1
            j += 1
            while cnt == 0:
                if j-i < d:
                    d = j-i
                    h = i
                if m[ord(s[i])] == 0:
                    cnt += 1
                m[ord(s[i])] = m[ord(s[i])] + 1
                i += 1
        if d == (1 << 30): return ""
        return s[h:h+d]

if __name__ == "__main__":
    s = "cabwefgewcwaefgcf"
    t = "cae"
    print(Solution().minWindow(s, t))
        


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值