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

Leetcode Minimum Window Substring

时间:2015-04-11 01:10:44      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:

题目地址:https://leetcode.com/problems/minimum-window-substring/

题目解答:

import java.util.HashMap;
import java.util.Map;

public class Solution {
    public String minWindow(String S, String T) {
        if(S == null || S.length() == 0 || T == null || T.equals("")){
            return "";
        }
        
        Map<Character,Integer> wordMap = new HashMap<Character,Integer>();
        
        //初始化T字符串中字符map
        for(int i = 0;i<T.length();i++){
            if(wordMap.containsKey(T.charAt(i))){
                wordMap.put(T.charAt(i),wordMap.get(T.charAt(i))+1);
            }else{
                wordMap.put(T.charAt(i),1);
            }
        }
        
        int start = 0;
        int end = 0;
        
        int foundCnt = 0;
        Map<Character,Integer> foundMap = new HashMap<Character,Integer>();
        String minWindow = "";
        int winLen = Integer.MAX_VALUE;
        
        //跳过S中不包含T中字符的部分
        while(start<S.length()&&!wordMap.containsKey(S.charAt(start))){
            start++;
            end++;
        }
        
        while(end < S.length()){
            //将S中找到的T中字符加到foundMap中
            if(wordMap.containsKey(S.charAt(end))){
                if(foundMap.containsKey(S.charAt(end))){ 
                    //只有foundMap中的value值小于wordMap中的值foundCnt才增加
                    if(foundMap.get(S.charAt(end)) < wordMap.get(S.charAt(end))){
                        foundCnt++;
                    }
                    foundMap.put(S.charAt(end),foundMap.get(S.charAt(end))+1);
                }else{
                    foundCnt++;
                    foundMap.put(S.charAt(end),1);
                }
            }
            
            //start到end包含了T中所有字符
            if(foundCnt == T.length()){
                //尽量缩短窗口
                while(!wordMap.containsKey(S.charAt(start)) || wordMap.get(S.charAt(start)) < foundMap.get(S.charAt(start))){
                    if(foundMap.containsKey(S.charAt(start))){
                        foundMap.put(S.charAt(start),foundMap.get(S.charAt(start)) - 1);
                    }
                    start++;
                }
                //更新minWindow
                minWindow = winLen > (end-start+1) ? S.substring(start,end+1):minWindow;
                winLen = winLen > (end-start+1) ? (end-start+1):winLen;
            }
            
            end++;
        }
        return minWindow;
    }
}

 

Leetcode Minimum Window Substring

标签:

原文地址:http://www.cnblogs.com/xiongyuesen/p/4416003.html

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