给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引?
输入:
s: "cbaebabacd" p: "abc"
输出:
[0, 6]
解释:
起始索引等于 0 的子串是 "cba", 它是 "abc" 的字母异位词。
起始索引等于 6 的子串是 "bac", 它是 "abc" 的字母异位词。
public static void main(String[] args) { int[] indexA = t(); for (int i = 0; i < indexA.length; i++) { System.out.print(indexA[i]); } } public static int[] t() { String st = "cbaebabacdabc"; String targetStr = "abc"; int startIndex = 0; int endIndex = targetStr.length(); int index = 0; int[] indexA = new int[st.length() - targetStr.length()]; for (int i = endIndex; i <= st.length(); i++) { boolean flag = repetitionSubStr(st, i - targetStr.length(), i, targetStr); System.out.println("===" + flag); if (flag) { indexA[index] = startIndex; index++; } startIndex++; i++; } return indexA; } public static boolean repetitionSubStr(String orgStr, int startIndex, int endIndex, String targetStr) { String orgStrTemp = orgStr.substring(startIndex, endIndex); System.out.print("orgStrTemp=" + orgStrTemp + "====endIndex=" + endIndex); char[] orgStrCharArray = orgStrTemp.toCharArray(); char[] targetStrCharArray = targetStr.toCharArray(); int len = targetStrCharArray.length; for (char s : orgStrCharArray) { for (int i = 0; i < targetStrCharArray.length; i++) { if (targetStrCharArray[i] != ' ' && s == targetStrCharArray[i]) { targetStrCharArray[i] = ' '; len--; continue; } } } return len == 0; }
算法参考:https://www.zhihu.com/question/314669016