问题:spa
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.string
The order of output does not matter.hash
Example 1:it
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:io
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".
解决:table
①anagrams,就是指顺序不一样但个数相同的字符串,使用滑动窗口,利用hash table的思想来比较每一个字符串中字符出现的个数是否相等。使用hp保存p,使用一个滑动窗口,长度为p.length( ),将s依次保存到hs中,判断两个hash table是否相等,若相等,就将第一个下标加入到返回链表中。耗时39ms。class
public class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> res = new ArrayList<>();
int hs[] = new int[256];
int hp[] = new int[256];
for (int i = 0;i < p.length();i ++ ) {
hp[p.charAt(i)] ++;
}
for (int i = 0;i < s.length();i ++) {
hs[s.charAt(i)] ++;
if(i >= p.length()){//滑动窗口
hs[s.charAt(i - p. length())] --;
}
if (Arrays.equals(hs,hp)) {
res.add(i - p.length() + 1);//返回起始下标
}
}
return res;
}
}变量
②利用滑动窗口的方法也比较巧妙,首先统计字符串p的字符个数,而后用两个变量left和right表示滑动窗口的左右边界,用变量count表示字符串p中须要匹配的字符个数,而后开始循环,若是右边界的字符已经在哈希表中了,说明该字符在p中有出现,则count自减1,而后哈希表中该字符个数自减1,右边界自加1,若是此时count减为0了,说明p中的字符都匹配上了,那么将此时左边界加入结果res中。若是此时right和left的差为p的长度,说明此时应该去掉最左边的一个字符,咱们看若是该字符在哈希表中的个数大于等于0,说明该字符是p中的字符,为啥呢,由于上面咱们有让每一个字符自减1,若是不是p中的字符,那么在哈希表中个数应该为0,自减1后就为-1,因此这样就知道该字符是否属于p,若是咱们去掉了属于p的一个字符,count自增1。耗时11ms.List
public class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> res = new LinkedList<>();
int[] hash = new int[256];//用于存放字符串p字符的个数
int left = 0;//滑动窗口的左边界
int right = 0;//右边界
char[] schar = s.toCharArray();
char[] pchar = p.toCharArray();
int count = pchar.length; //字符串p中须要匹配的字符个数
for (char c: pchar) hash[c]++;//统计字符串p中的字符个数
while (right < schar.length) {
char c = schar[right ++];
if (hash[c]-- >= 1)//右边界上的字符c在P中
count--;//须要匹配的字符减1
while (right - left > pchar.length) {//若是左右边界之差大于p的长度 char prev = schar[left++];//滑动窗口左边界需右移 if (hash[prev]++ >= 0) count++;//若是在滑动窗口范围外出现过一次,须要匹配的字符个数加1 } if (count == 0) res.add(left);//若是须要匹配的字符为0,说明s中有与p匹配的字符串,返回左边界便可 } return res; } }