/*
Acception of mine using template.
1. //create a hashmap to save the Characters of the target substring.
//(K, V) = (Character, Frequence of the Characters)
2. //maintain a counter to check whether match the target string.
//must be the map size, NOT the string size because the char may be duplicate.
3. //Two Pointers: begin - left pointer of the window; end - right pointer of the window
3. 减去已经出现的字符,如果counter==0,说明所有的字符已经找到,需要处理。和移动窗口(start,end)
4. //***be careful here: choose the char at begin pointer, NOT the end pointer,若果counter不为0,
说明还map.size()-counter个已经匹配,还需要匹配counter个字符。
*/
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> ans;
int begin = 0,end = 0;
map<char,int> mp; //first
for(char c:p) mp[c]++;
int counter = mp.size(); //second
int head=0,len=INT_MAX;
while(end<s.size())
{
char c = s[end];
if(mp.count(c)) {
if(--mp[c]== 0) counter--; //third
}
end++;
while(counter == 0)
{
char c = s[begin]; //fourth
if(mp.count(c)){
if(++mp[c]>0) counter++;
}
if((end-begin) == p.size()) // fifth
{
ans.push_back(begin);
}
begin++;
}
}
return ans;
}
};
/* The template
public class Solution {
public List<Integer> slidingWindowTemplateByHarryChaoyangHe(String s, String t) {
//init a collection or int value to save the result according the question.
List<Integer> result = new LinkedList<>();
if(t.length()> s.length()) return result;
//create a hashmap to save the Characters of the target substring.
//(K, V) = (Character, Frequence of the Characters)
Map<Character, Integer> map = new HashMap<>();
for(char c : t.toCharArray()){
map.put(c, map.getOrDefault(c, 0) + 1);
}
//maintain a counter to check whether match the target string.
int counter = map.size();//must be the map size, NOT the string size because the char may be duplicate.
//Two Pointers: begin - left pointer of the window; end - right pointer of the window
int begin = 0, end = 0;
//the length of the substring which match the target string.
int len = Integer.MAX_VALUE;
//loop at the begining of the source string
while(end < s.length()){
char c = s.charAt(end);//get a character
if( map.containsKey(c) ){
map.put(c, map.get(c)-1);// plus or minus one
if(map.get(c) == 0) counter--;//modify the counter according the requirement(different condition).
}
end++;
//increase begin pointer to make it invalid/valid again
while(counter == 0 // counter condition. different question may have different condition ){
char tempc = s.charAt(begin);//be careful here: choose the char at begin pointer, NOT the end pointer
if(map.containsKey(tempc)){
map.put(tempc, map.get(tempc) + 1);//plus or minus one
if(map.get(tempc) > 0) counter++;//modify the counter according the requirement(different condition).
}
// save / update(min/max) the result if find a target
// result collections or result int value
begin++;
}
}
return result;
}
}
*/
438. Find All Anagrams in a String
最新推荐文章于 2018-05-17 10:57:38 发布