码迷,mamicode.com
首页 > Windows程序 > 详细

Minimum Window Substring

时间:2014-06-29 20:38:14      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   string   

题目

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

方法

首先找到一个包含所有T的窗口,逐步右移。使用begin和end来标记窗口的起始。
    public String minWindow(String S, String T) {
        if (S == null || T == null) {
        	return null;
        }
        if (T.equals("") || S.equals("")) {
        	return "";
        }
        Map<Character, Integer> needFind = new HashMap<Character, Integer>();
        Map<Character, Integer> hasFind = new HashMap<Character, Integer>();
        
        int lenS = S.length();
        int lenT = T.length();
        for (int i = 0; i < lenT; i++) {
        	char ch = T.charAt(i);
        	if (!needFind.containsKey(ch)) {
        		needFind.put(ch, 1);
        		hasFind.put(ch, 0);
        	} else {
        		needFind.put(ch, needFind.get(ch) + 1);
        	}
        }
        
        int newBegin = -1;
        int newEnd = S.length();
        int count = 0;
        for (int begin = 0, end = 0; end < lenS; end++) {
        	char ch = S.charAt(end);
        	if (needFind.containsKey(ch)) {
        		hasFind.put(ch, hasFind.get(ch) + 1);
        		if (hasFind.get(ch) <= needFind.get(ch)) {
        			count++;
        		}
        		if (count == lenT) {
        			char temp = S.charAt(begin);
        			while(!needFind.containsKey(temp) || hasFind.get(temp) > needFind.get(temp)) {
        				
        				if (needFind.containsKey(temp) && hasFind.get(temp) > needFind.get(temp)) {
        					hasFind.put(temp, hasFind.get(temp) - 1);
        				}
        				
        				begin = begin + 1;
        				temp = S.charAt(begin);
        			}
        			
        			if (end - begin < newEnd - newBegin) {
        				newEnd = end;
        				newBegin = begin;
        			}
        		}
        	}
        }
        
        if (newBegin == -1) {
        	return "";
        } else {
        	return S.substring(newBegin, newEnd + 1);
        }       
    }


Minimum Window Substring,布布扣,bubuko.com

Minimum Window Substring

标签:java   leetcode   string   

原文地址:http://blog.csdn.net/u010378705/article/details/35572759

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!