Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
Example 1:
Input: s = "cbaebabacd", p = "abc"
Output: [0,6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
Example 2:
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".
Constraints:
1 <= s.length, p.length <= 3 * 104sandpconsist of lowercase English letters.
就是要找p在s里有多少anagram,相当于是在一个字符串中找满足每个字母出现某个频率的substring(anagram -> frequency)。说是sliding window,但其实这个window的长度是固定的,也就是其实并不需要left和right,一个index遍历就行了。以及要找字母出现的频率,对于string来说可以直接用char\[\]来记录char - 'a'比用map方便多了。
代码写起来比较直观,几个自己遇到的坑:
-
刚开始脑子没想明白,while写了半天,数组边界搞的乱七八糟。改用for以后固定只看后边界,就清楚多了。
-
要考虑p.length() < s.length()的情况
class Solution {
public ListfindAnagrams(String s, String p) {
Listresult = new ArrayList<>();
int[] pChars = new int[26];
int[] sChars = new int[26];
if (s.length() < p.length()) {
return result;
}
for (int i = 0; i < p.length(); i++) {
pChars[p.charAt(i) - 'a']++;
sChars[s.charAt(i) - 'a']++;
}
if (Arrays.equals(pChars, sChars)) {
result.add(0);
}for (int i = p.length(); i < s.length(); i++) { // remove first element in window sChars[s.charAt(i - p.length()) - 'a']--; // move window to the next sChars[s.charAt(i) - 'a']++; // update result if (Arrays.equals(pChars, sChars)) { result.add(i - p.length() + 1); } } return result; }}