LeetCode_438_FindAllAnagramsInAString
題目分析:
上一題只找一個(gè)鳄袍,這題找所有蚊伞。雙指針的思路不變燎斩,只是中途不return而已缨恒。
同時(shí)注意 s: "abab" p: "ab" 這個(gè)用例,不要找到一個(gè)串就跳過(guò)整個(gè)串搓逾。
解法:
public static List<Integer> findAnagrams(String s, String p) {
List<Integer> res = new LinkedList<>();
if (s.isEmpty()) return res;
int[] m = new int[128];
int left = 0, right = 0, cnt = p.length(), n = s.length();
for (char c : p.toCharArray()) ++m[c];
while (right < n) {
if (m[s.charAt(right++)]-- > 0) --cnt;
if (cnt == 0) res.add(left);
/**
* 利用了惰性判斷 right - left == p.length() 不成立時(shí)
* 右邊不會(huì)執(zhí)行卷谈,left也就不會(huì)遞增。
*/
if (right - left == p.length() && m[s.charAt(left++)]++ >= 0) ++cnt;
}
return res;
}