给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。

    字符串只包含小写英文字母,并且字符串 s 和 p 的长度都不超过 20100。

    说明:

    字母异位词指字母相同,但排列不同的字符串。

    不考虑答案输出的顺序。

    示例 1:

    输入:

    s: “cbaebabacd” p: “abc”

    输出:

    [0, 6]

    解释:

    起始索引等于 0 的子串是 “cba”, 它是 “abc” 的字母异位词。

    起始索引等于 6 的子串是 “bac”, 它是 “abc” 的字母异位词。

    示例 2:

    输入:

    s: “abab” p: “ab”

    输出:

    [0, 1, 2]

    解释:

    起始索引等于 0 的子串是 “ab”, 它是 “ab” 的字母异位词。

    起始索引等于 1 的子串是 “ba”, 它是 “ab” 的字母异位词。

    起始索引等于 2 的子串是 “ab”, 它是 “ab” 的字母异位词。

    来源:力扣(LeetCode)

    链接:https://leetcode-cn.com/problems/find-all-anagrams-in-a-string

    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    1. class Solution {
    2. public List<Integer> findAnagrams(String s, String p) {
    3. if (s.length() < p.length()) return Collections.emptyList();
    4. List<Integer> list = new ArrayList<>();
    5. int[] need = new int[26];
    6. int[] window = new int[26];
    7. int left = 0, right = 0, valid = 0, len = 0;
    8. for (char c : p.toCharArray()) {
    9. if (need[c - 'a'] == 0) len++;
    10. need[c - 'a']++;
    11. }
    12. char[] sarr = s.toCharArray();
    13. while (right < s.length()) {
    14. int index = sarr[right] - 'a';
    15. if (need[index] != 0) {
    16. window[index]++;
    17. if (need[index] == window[index]) {
    18. valid++;
    19. }
    20. }
    21. if (right - left + 1 == p.length()) {
    22. if (valid == len) {
    23. list.add(left);
    24. }
    25. int temp = sarr[left] - 'a';
    26. if (need[ temp ]!= 0) {
    27. if (window[temp] == need[temp])
    28. valid--;
    29. window[temp]--;
    30. }
    31. left++;
    32. }
    33. right++;
    34. }
    35. return list;
    36. }
    37. }

    https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/solution/hua-dong-chuang-kou-tong-yong-si-xiang-jie-jue-zi-/