?LeetCode刷題實戰(zhàn)438:找到字符串中所有字母異位詞
Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
示例
示例?1:
輸入: s = "cbaebabacd", p = "abc"
輸出: [0,6]
解釋:
起始索引等于 0?的子串是 "cba", 它是 "abc"?的異位詞。
起始索引等于 6?的子串是 "bac", 它是 "abc"?的異位詞。
示例 2:
輸入: s = "abab", p = "ab"
輸出: [0,1,2]
解釋:
起始索引等于 0?的子串是 "ab", 它是 "ab"?的異位詞。
起始索引等于 1?的子串是 "ba", 它是 "ab"?的異位詞。
起始索引等于 2?的子串是 "ab", 它是 "ab"?的異位詞。
解題

class?Solution?{
????public?ListfindAnagrams(String s, String p) {
????????char[] arrS = s.toCharArray();
????????char[] arrP = p.toCharArray();
????????
????????// 接收最后返回的結(jié)果
????????Listans = new?ArrayList<>();
????????
????????// 定義一個 needs 數(shù)組來看 arrP 中包含元素的個數(shù)
????????int[] needs = new?int[26];
????????// 定義一個 window 數(shù)組來看滑動窗口中是否有 arrP 中的元素,并記錄出現(xiàn)的個數(shù)
????????int[] window = new?int[26];
????????
????????// 先將 arrP 中的元素保存到 needs 數(shù)組中
????????for?(int?i = 0; i < arrP.length; i++) {
????????????needs[arrP[i] - 'a'] += 1;
????????}
????????
????????// 定義滑動窗口的兩端
????????int?left = 0;
????????int?right = 0;
????????
????????// 右窗口開始不斷向右移動
????????while?(right < arrS.length) {
????????????int?curR = arrS[right] - 'a';
????????????right++;
????????????// 將右窗口當前訪問到的元素 curR 個數(shù)加 1
????????????window[curR] += 1;
????????????
????????????// 當 window 數(shù)組中 curR 比 needs 數(shù)組中對應(yīng)元素的個數(shù)要多的時候就該移動左窗口指針
????????????while?(window[curR] > needs[curR]) {
????????????????int?curL = arrS[left] - 'a';
????????????????left++;
????????????????// 將左窗口當前訪問到的元素 curL 個數(shù)減 1
????????????????window[curL] -= 1;
????????????}
????????????
????????????// 這里將所有符合要求的左窗口索引放入到了接收結(jié)果的 List 中
????????????if?(right - left == arrP.length) {
????????????????ans.add(left);
????????????}
????????}
????????return?ans;
????}
}
LeetCode刷題實戰(zhàn)421:數(shù)組中兩個數(shù)的最大異或值
LeetCode刷題實戰(zhàn)423:從英文中重建數(shù)字
LeetCode刷題實戰(zhàn)424:替換后的最長重復(fù)字符
LeetCode刷題實戰(zhàn)426:將二叉搜索樹轉(zhuǎn)化為排序的雙向鏈表
LeetCode刷題實戰(zhàn)428:序列化和反序列化 N 叉樹
LeetCode刷題實戰(zhàn)429:N 叉樹的層序遍歷
LeetCode刷題實戰(zhàn)430:扁平化多級雙向鏈表
LeetCode刷題實戰(zhàn)431:將 N 叉樹編碼為二叉樹
LeetCode刷題實戰(zhàn)432:全 O(1) 的數(shù)據(jù)結(jié)構(gòu)
LeetCode刷題實戰(zhàn)434:字符串中的單詞數(shù)
LeetCode刷題實戰(zhàn)435:無重疊區(qū)間
LeetCode刷題實戰(zhàn)436:尋找右區(qū)間
