[leetCode]438. 找到字符串中所有字母异位词

题目

https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/
[leetCode]438. 找到字符串中所有字母异位词_第1张图片

滑动窗口

此题与 【567.字符串排列】解法一样。

class Solution {
    private List<Integer> res = new ArrayList<>();
    public List<Integer> findAnagrams(String s, String p) {
        int len = s.length();
        int windowSize = p.length();
        if (len < windowSize) return res;
        int[] pMap = new int[26];
        int[] sMap = new int[26];
        for (int i = 0; i < windowSize; i++) {
            pMap[p.charAt(i) - 'a']++;
            sMap[s.charAt(i) - 'a']++;
        }
        int count = 0;
        for (int i = 0; i < 26; i++) {
            if (pMap[i] == sMap[i])
                count++;
        }
        for (int i = 0; i < len - windowSize; i++) {
            if (count == 26) {
                res.add(i);
            }
            int left = s.charAt(i) - 'a';
            int right = s.charAt(i + windowSize) - 'a';
            sMap[right]++;
            if (sMap[right] == pMap[right])
                count++;
            else if (sMap[right] == pMap[right] + 1)
                count--;
            sMap[left]--;
            if (sMap[left] == pMap[left])
                count++;
            else if (sMap[left] == pMap[left] - 1)
                count--;
        }
        if (count == 26)
            res.add(len - windowSize);
        return res;
    }
}

你可能感兴趣的:(LeetCode,#,双指针法)