总结
- 一旦题目涉及找符合条件的subtring, 或者这个substring的起始位置, 或者subarray 的长度, 那么便可以用sliding window
- 如果给定两个字符串,那么需要一开始用map统计字符串p
- 如果只给定一个字符串,那么只需要map,不需要统计
- 模板的关键是要定义count, 也就是说要定义好begin++ 是的condition
- substring with concatenation of All words与其他题目不同的地方是
- 它的window size是确定不变的. 其他的是会变的. 所以前者没必要维护一个start指针和end指针, 而是维护一个外指针(确定window的起点), 一个内指针(确定window内字符串的起点)
- window size固定的一般暴力解法
- 一个hashmap, 0 < i <= s.length() - windowSize, 检验[i]是否符合要求, 若符合的话, map.get([i])--, 最后remove key, 直到map.size() == 0
- 注意: 模板中的结果更新有可能放在内循环里面或者放在内循环后面.
Template
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;
}