438. Find All Anagrams in a String - Medium
前往題目
之前寫的文章
想法
- 用
map
- 用
Sliding window
思路
- 備用
array
來儲存sliding window
的資訊,另一個array
用來儲存p
的counts
- 開始疊代
s
,每次循環都看看是否和p array
相等,超過p
的長度時就開始把p
長度之前的字母去掉,以保證window
的size
和p
的length
一樣 - 遇到
array
相等就加第一個字母的index
到結果中
Code
class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> res = new ArrayList<>();
// Array to count s
int[] S = new int[26];
// Array to count p
int[] P = new int[26];
// Store p's character count
for (char c : p.toCharArray()) {
P[c - 'a']++;
}
for (int i = 0; i < s.length(); ++i) {
// Count s's char
S[s.charAt(i) - 'a']++;
// Maintain the window size of s segment as large as p
// 這一步是保證window和p的size一樣,例如p是"abc"那size就是3,當i為2的時候不會符合條件,3的時候才會,這時window的size就是4了,所以要把頭去掉
if (i >= p.length()) {
// Remove the head
S[s.charAt(i - p.length()) - 'a']--;
}
// Compare
if (Arrays.equals(S, P)) {
res.add(i - p.length() + 1);
}
}
return res;
}
}
438. Find All Anagrams in a String - Medium
https://f88083.github.io/2024/04/09/438-Find-All-Anagrams-in-a-String-Medium/