Given a string s and a non-empty string starting index p, find all s is a substring of ectopic word letter p, and returns the substring.
String contains only lowercase letters, and the character string length p and s is not more than 20,100.
Description:
Ectopic word letters refer to the same letters, but arranged in different strings.
The order of the answers that were not considered.
Example 1:
Input:
S: "cbaebabacd" P: "ABC"
Output:
[0, 6]
Explanation:
The starting index of 0 is equal to the substring "cba", which is "abc" ectopic letter words.
6 substring starting index is equal to "bac", which is "abc" ectopic letter words.
Example 2:
Input:
S: "ABAB" P: "ab &"
Output:
[0, 1, 2]
Explanation:
The starting index of 0 is equal to the substring "ab", which is "ab" ectopic letter words.
Substring starting index 1 is equal to "ba", which is "ab" ectopic letter words.
2 substring starting index is equal to "ab", which is "ab" ectopic letter words.
Ideas:
Classic sliding window algorithm, while the use of int [26] array to store the index is recorded letters appear char - 'a', that an element increases or decrease the draw window assigned to the recording value.
Taobao:
class Solution {
public List<Integer> findAnagrams(String s, String p) {
if(s.equals("")) return new ArrayList<>();
if(s.length()<p.length()) return new ArrayList<>();
int[] record1 = new int[26];
int[] record2 = new int[26];
ArrayList<Integer> res = new ArrayList<>();
int l=0, r= p.length()-1;
for(char c: p.toCharArray()){
record1[c-'a']++;
}
for(int i=0; i<=r; i++){
record2[s.charAt(i)-'a']++;
}
while(r<s.length()){
if(Arrays.equals(record1,record2)){
res.add(l);
}
l++;
r++;
if(r<s.length()){
record2[s.charAt(r)-'a']++;
record2[s.charAt(l-1)-'a']--;
}
}
return res;
}
}