zoukankan      html  css  js  c++  java
  • Java for LeetCode 076 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".

    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放进tMap中,同时创建一个保存T中所有字符(不重复)的图sMap,用一个计数器表示sMap和tMap的重合程度,一旦sMap包含了tMap即找到了一组解,通过收缩begin指针获取刚好包含tMap的位置,之后就是比较大小了,JAVA实现如下:

     public String minWindow(String s, String t) {
            HashMap<Character, Integer> tMap = new HashMap<Character, Integer>();
            HashMap<Character, Integer> sMap = new HashMap<Character, Integer>();
            for (int i=0;i<t.length();i++){
            	sMap.put(t.charAt(i), 0);  
                if (!tMap.containsKey(t.charAt(i)))
                    tMap.put(t.charAt(i), 1);
                else
                    tMap.put(t.charAt(i), tMap.get(t.charAt(i)) + 1); 
            }
            int begin=0,count=0,minBegin=0,length=s.length()+1;;
            for(int i=0;i<s.length();i++){
            	if(!tMap.containsKey(s.charAt(i)))
            		continue;
            	sMap.put(s.charAt(i), sMap.get(s.charAt(i))+1);
            	if(sMap.get(s.charAt(i))<=tMap.get(s.charAt(i)))
            		count++;
            	if(count==t.length()){
            		for(int j=begin;j<=i;j++){
            			if(!tMap.containsKey(s.charAt(j)))
            				continue;
            			if(sMap.get(s.charAt(j))>tMap.get(s.charAt(j))){
            				sMap.put(s.charAt(j),sMap.get(s.charAt(j))-1);
            				continue;
            				}
            			sMap.put(s.charAt(j),sMap.get(s.charAt(j))-1);
            			count--;
            			begin=j+1;
            			if(length>i-j){
            				length=i-j;
            				minBegin=j;
            			}
            			break;
            		}
            	}
            }
            return length!=s.length()+1?s.substring(minBegin, minBegin+length+1):"";
        }
    
  • 相关阅读:
    package.json文件
    Node.js中模块加载机制
    第三方模块
    系统模块
    Node.js快速入门及模块化开发
    String 的扩展方法
    ES6 的内置对象扩展
    箭头函数
    解构赋值
    let、const、var 的区别
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4513049.html
Copyright © 2011-2022 走看看