LeetCode438 FindAllAnagramsInAString
题目描述
给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。
字符串只包含小写英文字母,并且字符串 s 和 p 的长度都不超过 20100。
说明:
- 字母异位词指字母相同,但排列不同的字符串。
- 不考虑答案输出的顺序。
示例1:
输入:
s: “cbaebabacd” p: “abc”输出:
[0, 6]解释:
起始索引等于 0 的子串是 “cba”, 它是 “abc” 的字母异位词。
起始索引等于 6 的子串是 “bac”, 它是 “abc” 的字母异位词。
示例2:
输入:
s: “abab” p: “ab”输出:
[0, 1, 2]解释:
起始索引等于 0 的子串是 “ab”, 它是 “ab” 的字母异位词。
起始索引等于 1 的子串是 “ba”, 它是 “ab” 的字母异位词。
起始索引等于 2 的子串是 “ab”, 它是 “ab” 的字母异位词。
解答
解法一:滑动窗口(hashmap)
在之前的滑动窗口的题目中,比如Leetcode上的第3和209,都没有必要特地记录下窗口中的所有字母,只是挨个遍历一下就可以(我之前的做法就是这样的)。但本例子中不同的是我们需要记录下来窗口中含有的字母。我们还需要另一个空间来记录给定的字符串的构成,所以需要两个hashmap.
基本思路是:窗口的右边界一直移动直到窗口中包含所有需要的字符。然后移动左边界,当窗口中的字符串满足要求是异位串时,记录左边界的值。每次左边界移动一位,都要判断此时窗口中是否还含有所有需要的字符,然后才判断是不是异位串,如果没有包含所有需要的字符,则移动右边界。
注意:本例中滑动窗口没有eetcode上第3题的优化,左边界必须一个一个移动,而不能在找到一个异位串时直接就左边界跳到右边界位置上,会有遗漏答案。
另外,临界值和更新一些变量时如匹配度match,要格外注意各种情况。
public static List<Integer> solve(String s, String p){
List<Integer> result = new ArrayList<>();
if (s==null ||s.length()==0)
return result;
Map<Character,Integer> windows = new HashMap<>();
Map<Character,Integer> need = new HashMap<>();
int l=0,r=0; //子串是[l,r],判断其中是不是字符串p的异位字符串。
int len = s.length();
int match = 0; //记录 window 中已经有多少字符符合要求了
//记录非空串p的构成情况。
for (int i=0;i<p.length();i++){
char c = p.charAt(i);
int temp =1; //对于下面几行代码,是因为如果map中一开始没有存放该字符的话,就会返回空对象
if (need.containsKey(c)){ //所以先做了个判断,但是后来才意识到有个need.getOrDefault()方法
temp =need.get(c)+1;
}
need.put(c,temp);
}
while (r<len){
char current = s.charAt(r);
int temp = 1;
if (windows.containsKey(current)){
temp =windows.get(current)+1;
}
windows.put(current,temp);
//计算窗口中有多少个已经满足条件的字符
if (need.containsKey(current) && temp==need.get(current)){
match++; //更新匹配度
}
//找到包含所有需要的字符的窗口以后
while (match==need.size()){
if (r-l+1==p.length() && !result.contains(l)){ //是异位串时,存储开始的索引,
result.add(l);
}
char cL = s.charAt(l);
int countL = windows.get(cL)-1;
windows.put(cL,countL);
if (need.containsKey(cL) && countL<need.get(cL)){ //更新匹配度
match--;
}
l++;
}
r++;
}
return result;
}
####解法二:滑动窗口(数组)
同样是滑动窗口,不用map, 用数组,会更方便 。ASCII码中97~122号为26个小写英文字母。事实上,更快,也更容易理解。
public static List<Integer> solve2(String s, String p){
List<Integer> result = new ArrayList<>();
if (s==null ||s.length()==0)
return result;
int[] windows = new int[26];
int[] need = new int[26];
int left=0, right=0; //[left,right]为窗口
int len = s.length();
int match =0; //匹配度
int kind = 0; //统计p中出现的字符种类。
//统计p的字符构成。
for (int i=0;i<p.length();i++){
need[p.charAt(i)-97]++; //减97是为了将字符都放在0-25的索引位置上。
if(need[p.charAt(i)-97]==1)
kind++;
}
while (right<len){
char c = s.charAt(right);
windows[c-97]++;
if (windows[c-97]==need[c-97]){
match++;
}
while (match==kind){
if (right-left+1==p.length()){ //符合条件的异位串
result.add(left);
}
char leftChar = s.charAt(left);
windows[leftChar-97]--;
if (windows[leftChar-97]<need[leftChar-97]){
match--;
}
left++;
}
right++;
}
return result;
}
PS:这题在LeetCode上标注的还是easy。wtf???dbq还是我太菜了,边界值和各种判断条件改了好多次。