[抄題]:算法
給定一個字符串 s
和一個 非空字符串 p
,找到在 s
中全部關於 p
的字謎的起始索引。
字符串僅由小寫英文字母組成,字符串 s 和 p 的長度不得大於 40,000。
輸出順序可有可無.數組
樣例數據結構
給出字符串 s = "cbaebabacd"
p = "abc"
返回 [0, 6]
ide
子串起始索引 index = 0 是 "cba",是"abc"的字謎. 子串起始索引 index = 6 是 "bac",是"abc"的字謎.
[暴力解法]:spa
時間分析:debug
空間分析:指針
[思惟問題]:rest
[一句話思路]:code
先初始化,再統計p位以後的絕對值之和。blog
[輸入量]:空: 正常狀況:特大:特小:程序裏處理到的特殊狀況:異常狀況(不合法不合理的輸入):
[畫圖]:
sliding window的原理是數數字,向右滑動時,count(r)++,count(l)--
[一刷]:
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分鐘肉眼debug的結果]:
[總結]:
根據表格進行聯想
[複雜度]:Time complexity: O(n) Space complexity: O(n)
[英文數據結構或算法,爲何不用別的數據結構或算法]:
[其餘解法]:
[Follow Up]:
[LC給出的題目變變變]:
242. Valid Anagram 用deta求absSum
567. Permutation in String 兩根指針?不懂
[代碼風格] :
public class Solution { /** * @param s: a string * @param p: a string * @return: a list of index */ public List<Integer> findAnagrams(String s, String p) { //initialization List<Integer> ans = new LinkedList<>(); //corner case if (s.length() < p.length()) { return ans; } char[] sc = s.toCharArray(); char[] pc = p.toCharArray(); int[] cntS = new int[256]; int[] cntP = new int[256]; int[] det = new int[256]; //count first int absSum = 0; for (int i = 0; i < p.length(); i++) { cntS[sc[i]]++; cntP[pc[i]]++; det[sc[i]]++; det[pc[i]]--; } for (int item : det) { absSum += Math.abs(item); } if (absSum == 0) { ans.add(0); } //count rest for (int i = p.length(); i < s.length(); i++) { int r = sc[i]; int l = sc[i - p.length()]; System.out.println("sc[i]="+sc[i]); System.out.println("r="+r); cntS[r]++;//both s cntS[l]--; absSum = absSum - Math.abs(det[r]) - Math.abs(det[l]);//abs det[l]--; det[r]++; absSum = absSum + Math.abs(det[r]) + Math.abs(det[l]); if (absSum == 0) { ans.add(i - p.length() + 1); } } return ans; } }