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.
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".
class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> res = new ArrayList<>();
if (s == null || p == null || s.length() == 0 || p.length() == 0) return res;
int len = p.length();
for (int i = 0; i <= s.length() - len; i++) {
if (isAna(s.substring(i, i + len), p)) {
res.add(i);
}
}
return res;
}
private boolean isAna(String s, String p) {
int[] hash = new int[26];
for (int i = 0; i < p.length(); i++) {
hash[p.charAt(i) - 'a']++;
hash[s.charAt(i) - 'a']--;
}
for (int c : hash) {
if (c != 0) return false;
}
return true;
}
}
class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> res = new ArrayList<>();
if (s == null || p == null || s.length() == 0 || p.length() ==0) return res;
// 记录p里letter出现的频率
int[] hash = new int[256];
for (char c : p.toCharArray()) hash[c]++;
//counter is a number to record whether we have a anagram which has equal length as p
int left = 0, right = 0, counter = p.length();
while (right < s.length()) {
// there is p's char in s,把counter减少1
char curr = s.charAt(right);
if (hash[curr] >= 1) counter--;
// 如果counter==0,说明每个在p里的字母都在s里找到了
if (counter == 0) res.add(left);
// hash table decreases the right char by 1
hash[curr]--;
right++; //move the sliding window to one step right
//if the window's size equals p, then we have to move left (narrow the window) to find the new match window
if (right - left == p.length()) {
// only increase the count if the character is in p,因为之前只有这样的条件才会count--
if (hash[s.charAt(left)] >= 0) counter++;
// 因为之前减少过hash[curr]--, 马上要移动left坐标,所以这里需要加1回来
hash[s.charAt(left)]++;
left++;
}
}
return res;
}
}