/** * 76. Minimum Window Substring * æ»å¨çªå£ãç¨iåjåå«æç¤ºçªå£ç两端ã * å¤§ä½æè·¯ï¼ * * åå§åï¼iåjé½ä¸º0. * whileï¼jè¿æ²¡æå°å°¾é¨ï¼ï¼ * * å°jå¾å³ç§»å¨ï¼ç´å°è¦çææéè¦çå ç´ ã * * å°iå¾å³ç§»å¨ï¼å»é¤ä¸å¿ è¦çé¨åã * * è®¡ç®æ¤æ¶ççªå£é¿åº¦ï¼ä¸ä¹åç使¯è¾ï¼åæå°å¼ã * * å°iå¾å³ç§»å¨ä¸ä½ï¼ä½¿çªå£ä¸æ»¡è¶³æ¡ä»¶ï¼ç¶åéå¤ç¬¬ä¸æ¥ã * * 注æå 为charæ¯8ä½ï¼æä»¥å¯ä»¥ç¨128个å ç´ çæ°ç»ä»£æ¿åå¸ã * @author LBW */ public class MinimumWindowSubstring { public String minWindow(String s, String t) { int[] need = new int[128]; for (char c: t.toCharArray()) { need[c] += 1; } int needCount = t.length(); int res = Integer.MAX_VALUE, start = 0; int i = 0, j = 0; while (j < s.length()) { if (need[s.charAt(j)] > 0) { needCount -= 1; } need[s.charAt(j)] -= 1; if (needCount == 0) { // æ¤æ¶è¯´ææ»å¨çªå£éæäºè¯¥æçå ç´ // å°è¯å°iå¾å³ç§»ï¼å¾å°æå°é¿åº¦ while (need[s.charAt(i)] < 0) { need[s.charAt(i)] += 1; i += 1; } if (j - i + 1 < res) { res = j - i + 1; start = i; } res = Math.min(res, j - i + 1); // å°iå¾å³ç§»å¨ä¸ä½ï¼å¾ªç¯ä»¥ä¸æ¥éª¤ need[s.charAt(i++)] += 1; needCount += 1; } j += 1; } if (res == Integer.MAX_VALUE) { return ""; } else return s.substring(start, start + res); } }