lc76 Minimum Window Substring數組
haspmap(也能夠用數組[26])和雙指針spa
hashmap用來統計target字符串每種字符的個數,以此來檢測source子串是否知足條件指針
雙指針,code
一個right用來遍歷source字符串,也是計算知足條件子串長度時的右側邊界blog
一個left是左側邊界 每次碰到知足條件的子串,left一直更新,直到left所指元素爲target不可或缺的一部分,即去掉left所指元素這個子串就不知足題意字符串
1 class Solution { 2 public String minWindow(String s, String t) { 3 if(s == null || s.length() < t.length() || t == null) 4 return ""; 5 char[] ss = s.toCharArray(); 6 char[] tt = t.toCharArray(); 7 8 HashMap<Character, Integer> map = new HashMap<>(); 9 10 int left = 0; 11 int count = 0; 12 int minLen = ss.length + 1; 13 int minLeft = 0; 14 for(char i : tt){ 15 if(!map.containsKey(i)){ 16 map.put(i, 1); 17 }else{ 18 map.put(i, map.get(i) + 1); 19 } 20 } 21 22 for(int right = 0; right < ss.length; right++){ 23 if(map.containsKey(ss[right])){ 24 map.put(ss[right], map.get(ss[right]) - 1); 25 if(map.get(ss[right]) >= 0) 26 count++; 27 while(count == tt.length){ 28 if(right - left + 1 < minLen){ 29 minLeft = left; 30 minLen = right - left + 1; 31 } 32 if(map.containsKey(ss[left])){ 33 map.put(ss[left], map.get(ss[left]) + 1); 34 if(map.get(ss[left]) > 0) 35 count--; 36 } 37 left++; 38 } 39 } 40 } 41 if(minLen > ss.length) 42 return ""; 43 44 return s.substring(minLeft, minLeft + minLen); 45 } 46 }