[Sliding window] 438. Find all anagrams in a string

438. Find All Alphabetic Words in a String

Given two strings s and p, find all anagram substrings of p in s, and return the starting indices of these substrings. The order in which answers are output is not considered.

An anagram refers to a character string formed by rearranging the same letter (including the same character string).

Example 1:

输入: s = "cbaebabacd", p = "abc"
输出: [0,6]
解释:
起始索引等于 0 的子串是 "cba", 它是 "abc" 的异位词。
起始索引等于 6 的子串是 "bac", 它是 "abc" 的异位词。

Example 2:

输入: s = "abab", p = "ab"
输出: [0,1,2]
解释:
起始索引等于 0 的子串是 "ab", 它是 "ab" 的异位词。
起始索引等于 1 的子串是 "ba", 它是 "ab" 的异位词。
起始索引等于 2 的子串是 "ab", 它是 "ab" 的异位词。

hint:

1 <= s.length, p.length <= 3 * 104
s 和 p 仅包含小写字母

answer:

class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> result = new ArrayList<>();
        // 使用双指针+位图
        int n = s.length();
        int m = p.length();
        // 
        if (m > n) {
            return new ArrayList<>();
        }
        // p 在位图中的位置
        int[] needs = new int[26];
        for (int i=0;i<m;i++) {
            needs[p.charAt(i) - 'a']++;
        }
        // 使用窗口滑动 s
        int start = 0;
        int end = 0;
        int[] matched = new int[26]; // 窗口
        // 先比较前m个字符
        while (end < m) {
            matched[s.charAt(end)-'a']++;
            end++;
        }
        if (same(needs, matched)) {
            result.add(start);
        }
        while (start<n && end<n) {
            // 滑动窗口
            matched[s.charAt(start)-'a']--;
            matched[s.charAt(end)-'a']++;
            start++;
            end++;
            if (same(needs, matched)) {
                result.add(start);
            }
        }
        return result;
    }

    public boolean same(int[] needs, int[] matched) {
        for (int i=0;i<needs.length;i++) {
            if (needs[i] != matched[i]) {
                return false;
            }
        }
        return true;
    }
}

Guess you like

Origin blog.csdn.net/wjavadog/article/details/126444440