1. 程式人生 > >76-最小視窗子串

76-最小視窗子串

Description:

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.

問題描述
給定字串S和T,在O(n)的時間複雜度下找出S中包含T所有字元的最小視窗。
例如,S = “ADOBECODEBANC”, T = “ABC”, 返回”BANC”

解法

class Solution {
    public String minWindow(String s, String t) {
        int
[] map = new int[128]; for(char c : t.toCharArray()) map[c]++; int counter = t.length(), start = 0, end = 0, d = Integer.MAX_VALUE, minstart = 0; while(end < s.length()){ char c = s.charAt(end); if(map[c] > 0) counter--; map[c]--; end++; while
(counter == 0){ if(end - start < d){ d = end - start; minstart = start; } char c1 = s.charAt(start); if(map[c1] == 0) counter++; map[c1]++; start++; } } return d == Integer.MAX_VALUE ? "" : s.substring(minstart, minstart + d); } }