Solution#3
public class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> list = new ArrayList<>();
if (s == null || s.length() == 0 || p == null || p.length() == 0) return list;
char[] pc = p.toCharArray();
char[] sc = s.toCharArray();
int fast = 0, slow = 0;
int count = pc.length;
int[] table = new int[26];
for (char c : pc) {
table[c - 'a']++;
}
while (fast < sc.length) {
if (--table[sc[fast++] - 'a'] >= 0) {
count--;
}
if (count == 0) {
list.add(slow);
}
if (fast - slow == pc.length && table[sc[slow++] - 'a']++ >= 0) {
count++;
}
}
return list;
}
}
Solution#2
Solution#1
public class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> result = new ArrayList<>();
int[] table = new int[26];
int pLength = p.length();
for (int i = 0; i < pLength; i++) {
table[p.charAt(i) - 'a']++;
}
int[] tmp = new int[26];
System.arraycopy(table, 0, tmp, 0, 26);
int count = 0;
for (int i = 0; i < s.length() - pLength + 1; i++) {
if (table[s.charAt(i) - 'a'] > 0) {
table[s.charAt(i) - 'a']--;
count++;
for (int j = 1; j < pLength; j++) {
if (--table[s.charAt(i + j) - 'a'] < 0) break;
count++;
}
if (count == pLength) result.add(i);
count = 0;
System.arraycopy(tmp, 0, table, 0, 26);
}
}
return result;
}
}
Problem#2
* 滑窗法没有掌握
Problem#1
*
O(n2)
时间复杂度
* 用滑窗法