给定一个字符串 S 和一个字符串 T,请在 S 中找出包含 T 所有字母的最小子串?
输入: S = "ADOBECODEBANC", T = "ABC"
输出: "BANC"
public static void main(String[] args) { System.out.println(t()); } public static String t() { String st = "ADOBECODEBANC"; String subSt = "ABC"; int startIndex = 0; int endIndex = 0; String strMinLen = ""; while (endIndex <= st.length() && startIndex <= endIndex) { boolean flag = containSubStr(st, startIndex, endIndex, subSt); if (!flag) { endIndex++; } if (flag) { strMinLen = "".equals(strMinLen) ? st.substring(startIndex, endIndex) : (strMinLen.length() > st.substring(startIndex, endIndex).length() ? st.substring(startIndex, endIndex) : strMinLen); startIndex++; } } return strMinLen; } public static boolean containSubStr(String orgStr, int startIndex, int endIndex, String subStr) { String orgStrTemp = orgStr.substring(startIndex, endIndex); System.out.println("orgStrTemp=" + orgStrTemp); char[] orgStrCharArray = orgStrTemp.toCharArray(); char[] subCharArray = subStr.toCharArray(); int subLen = subCharArray.length; for (char s : subCharArray) { for (char o : orgStrCharArray) { if (s == o) { subLen--; break; } } } return subLen <= 0; }
算法参考:https://www.zhihu.com/question/314669016