Java Solution


  • 0
    M
        public String minWindow(String s, String t) {
            if (s == null || t == null) return "";
    		int m = s.length(), n = t.length();
    		int[] toFind = new int[128];
    		Set<Character> set = new HashSet<>();
    		int cnt = 0;
    		for (char c : t.toCharArray()) {
    			++toFind[c];
    			set.add(c);
    			++cnt;
    		}
    		int minLen = Integer.MAX_VALUE;
    		String res = "";
    		int i = 0;
    		for (int j = 0; j < m; ++j) {
    			char c = s.charAt(j);
    			if (set.contains(c)) {
    				if (--toFind[c] >= 0) {
    					--cnt;
    				}
    				while (cnt == 0 && i <= j) {
    					if (j - i + 1 < minLen) {
    						minLen = j - i + 1;
    						res = s.substring(i, j + 1);
    					}
    					int pre = s.charAt(i);
    					if (set.contains(pre) && ++toFind[pre] > 0) ++cnt;
    					++i;
    				}
    			}
    		}
    		return res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.