力扣438.找到字符串中所有字母异位词(滑动窗口)

  • 判断是否为异位词我最开始想的是通过转换成数组进行sort排序再使用equals进行比较的,这里采用的是使用cnt数组进行计数,最后直接使用Array中的equals方法比较两个数组是否相同来进行判断
  • 除了数组,也可以使用HashMap进行计数判断,最后也可以通过Map.equals直接进行判断两个Map是否相等
class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        int[] cntP = new int[26];
        for (char c : p.toCharArray()) {
            cntP[c - 'a']++;
        }
        int n = s.length();
        int m = p.length();
        List<Integer> ans = new ArrayList<>();
        int[] cntS = new int[26];
        for (int i = 0; i < n; i++) {
            cntS[s.charAt(i) - 'a']++;
            int left = i - m + 1;
            if (left < 0) {
                continue;
            }
            if (Arrays.equals(cntS, cntP)) {
                ans.add(left);
            }
            cntS[s.charAt(left) - 'a']--;
        }
        return ans;
    }
}
posted @ 2026-01-23 14:18  Huangyien  阅读(2)  评论(0)    收藏  举报