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.
package leetCode; /** * Created by lxw, liwei4939@126.com on 2018/3/11. */ public class L076_Minimum_Window_Substring { public String minWindow(String str1, String str2){ if (str1 == null || str2 == null || str1.length() < str2.length()){ return ""; } char[] chas1 = str1.toCharArray(); char[] chas2 = str2.toCharArray(); int[] map = new int[256]; for (int i = 0; i < chas2.length; i++){ map[chas2[i]]++; } int left = 0; int right = 0; int match = chas2.length; int minLen = chas1.length + 1; String res = ""; while (right != chas1.length){ map[chas1[right]]--; if (map[chas1[right]] >= 0){ match--; } if (match == 0){ while (map[chas1[left]] < 0){ map[chas1[left++]]++; } if (minLen > right - left +1){ minLen = right - left +1; res = str1.substring(left, right + 1); } } right++; } return res; } public static void main(String[] args){ L076_Minimum_Window_Substring tmp =new L076_Minimum_Window_Substring(); String str1 = "ADOBECODEBANC"; String str2 = "ABC"; System.out.println(tmp.minWindow(str1, str2)); } }
本文介绍了一种在字符串S中寻找包含字符串T所有字符的最短子串的高效算法,复杂度为O(n)。通过具体示例展示了如何实现该算法,并提供了完整的Java代码实现。

817

被折叠的 条评论
为什么被折叠?



