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> list = new ArrayList<Integer>();
if (s == null || s.length() == 0 || p == null || p.length() == 0) return list;
int[] map = new int[256]; // char map {char: freq}
for (char ch : p.toCharArray()) {
map[ch]++;
}
int count = p.length();
int left = 0; int right = 0;
while (right < s.length() ) {
// find a matching char
if (map[s.charAt(right)] > 0) count--;
map[s.charAt(right)]--;
right++;
// find an anagram
if (count == 0) list.add(left);
// reset count and map using left pointer
if (right - left == p.length()) {
if (map[s.charAt(left)] >= 0) count++;
map[s.charAt(left)]++;
left++;
}
}
return list;
}
}
Complexity Analysis
Time Complexity: O(n). 我们的左右指针会以sliding window的方式各自遍历整个数组。
Space Complexity: O(1). 我们虽然使用了map来储存字母出现次数,但是由于字母个数的有限的(255),这个map只会占用constant space。
int findSubstring(string s){
vector<int> map(128,0);
int counter; // check whether the substring is valid
int begin=0, end=0; //two pointers, one point to tail and one head
int d; //the length of substring
for() { /* initialize the hash map here */ }
while(end<s.size()){
if(map[s[end++]]-- ?){ /* modify counter here */ }
while(/* counter condition */){
/* update d here if finding minimum*/
//increase begin to make it invalid/valid again
if(map[s[begin++]]++ ?){ /*modify counter here*/ }
}
/* update d here if finding maximum*/
}
return d;
}