問題: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; } }