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

2021-10-15  本文已影响0人  justonemoretry
image.png

解法

class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        int m = s.length();
        int n = p.length();
        List<Integer> res = new ArrayList<>();
        if (n > m) {
            return res;
        }

        int[] sCount = new int[26];
        int[] pCount = new int[26];
        // 统计p中出现字符个数
        for (int i = 0; i < n; i++) {
            pCount[p.charAt(i) - 'a']++;
        }
        // s字符双指针滑动
        int left= 0;
        for (int right = 0; right < m; right++) {
            int rightIndex = s.charAt(right) - 'a';
            sCount[rightIndex]++;
            // s中的元素多于p时,左边弹出,直到相等
            while (sCount[rightIndex] > pCount[rightIndex]) {
                int leftIndex = s.charAt(left) - 'a';
                sCount[leftIndex]--;
                left++;
            }
            // 每一个值都经过比较,所以是相等的
            if (right - left + 1 == n) {
                res.add(left);
            }    
        }
        return res;
    }
}
上一篇下一篇

猜你喜欢

热点阅读