子串字謎substring anagrams

[抄題]:算法

給定一個字符串 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)--

[一刷]:

  1. 字符串處理一個個的字母時,要用.tochararray先把字符串轉成數組
  2. det也是數組,absSum是其的絕對值求和
  3. det 有幾個元素算幾個,用for (int item : det)簡寫
  4. s.toCharArray();表示對方法的調用
  5. list必定要用linkedlist or arraylist來實現,不能直接複製粘貼

[二刷]:

  1. 特殊判斷必需要寫
  2. 搞清楚det的含義 = sc - pc pc增長,det = r - l r增長
  3. 在以後的數組中,都是計算cntS[] 數組的數量
  4. absSum要用Math.abs

[三刷]:

[四刷]:

[五刷]:

  [五分鐘肉眼debug的結果]:

[總結]:

根據表格進行聯想

[複雜度]:Time complexity: O(n) Space complexity: O(n)

[英文數據結構或算法,爲何不用別的數據結構或算法]:

[其餘解法]:

[Follow Up]:

[LC給出的題目變變變]:

242. Valid Anagram 用deta求absSum

567. Permutation in String 兩根指針?不懂

 [代碼風格] :

  1. cntS 才符合駱駝命名法
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; } }
View Code
相關文章
相關標籤/搜索