【字符串】B047_LC_找到字符串中所有字母異位詞(滑動窗口)

一、Problem

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.

Input:
s: "abab" p: "ab"

Output:
[0, 1, 2]

Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".

二、Solution

方法一:滑動窗口\

  • 窗口的含義
    • 囊括合法子串
  • 窗口右移時機
    • 每次都右移
  • 窗口左移時機
    • 因爲要找的是字母異位詞,所以出現字符的出現次數必須嚴格相等,所以噹噹前字符的出現此次數 wins[cr] > needs[cr] 時,那麼我們可以認爲這個此時的窗口內部的子串肯定不是想要的子串。
    • 故通過縮小窗口左邊界至窗口不包含重複字符 win[cr] 爲止。
  • 結算時機
    • 當窗口內部子串合法且長度等於 p.length
class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> res = new LinkedList<>();
        int l = 0, r = 0, n = s.length(), m = p.length(), needs[] = new int[258], win[] = new int[258];
        for (char c : p.toCharArray()) needs[c]++;

        while (r < n) {
            char cr = s.charAt(r);
            ++win[c];
            while (win[cr] > needs[c]) {
                char cl = s.charAt(l);
                win[cl]--;
                l++;
            }
            if (r - l + 1 == m) 
                res.add(l);
            r++;
        }
        return res;
    }
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(1)O(1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章