题目: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.
示例: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”.
思路:题目的关键是判断s的一个字串是否为p的anagrams。之前有道题就是起到这个作用,有兴趣的同学可以去看看。这里仍适用该思路进行判断。代码如下所示:
public static List<Integer> findAnagrams(String s, String p) {
List<Integer> list = new ArrayList<Integer>();
if(s == null || p == null || s.length() < p.length()) return list;
int lengthp = p.length();
int lengths = s.length();
int[] hash = new int[26];
//将字符串p的信息保存在hash数组中
for(char c : p.toCharArray()){
++hash[c - 'a'];
}
int left = 0, right = 0;
while(right < lengths){
//如果s中right处的字符在p中,则将hash数组中相应计数减一。且如果该数字大于0说明仍然属于p的anagrams范畴。将lengthp--。
if(hash[s.charAt(right++) - 'a']-- > 0) lengthp--;
//当lengthp==0时表明left-right中的子串属于p的anagrams,记录该索引位置
if(lengthp == 0) list.add(left);
//当发现一个anagrams后,再将其信息录入到hash数组中。即相当于将p的数据再次保存。且将lengthp也恢复原来的大小
if(right - left == p.length() && hash[s.charAt(left++) - 'a']++ >= 0) lengthp++;
}
//最终返回list即可
return list;
}