LeetCode -Find All Anagrams in a String 找到给定字符串中所有字符的子串

190 阅读1分钟

Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.

Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.

The order of output does not matter.

大意:给定小串p,在大串s中找到包含p所有字符的子串。

解题:使用滑动窗口(slide window),迭代s,

    1. 如果numbers[windowEnd]的个数大于0,则个数--,windowEnd前移++。如果windowEnd - windowStart == p.length(),添加到结果中。
    1. 如果windowStart == windowEnd,则窗口左右一起前移
    1. 否则numbers[windowStart++]++,即窗口左边前移即可。
public List<Integer> findAnagrams(String s, String p) {
    List<Integer> result = new ArrayList();
    int[] numbers = new int[26];
    
    for(int i=0; i<p.length(); i++) {
        numbers[p.charAt(i) - 'a']++;
    }
    int windowStart = 0;
    int windowEnd   = 0;
    while(windowEnd < s.length()) {
        if(numbers[s.charAt(windowEnd) - 'a'] > 0) {
            numbers[s.charAt(windowEnd++) - 'a']--;
            if(windowEnd - windowStart == p.length()) {
                result.add(windowStart);
            }
        }else if(windowStart == windowEnd) {
            windowStart++;
            windowEnd++;
        }else {
            numbers[s.charAt(windowStart++) - 'a']++;
        }
    }
    return result;
}