美文网首页
438. 找到字符串中所有字母异位词

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

作者: justonemoretry | 来源:发表于2021-10-15 00:07 被阅读0次
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;
    }
}

相关文章

网友评论

      本文标题:438. 找到字符串中所有字母异位词

      本文链接:https://www.haomeiwen.com/subject/kwupoltx.html