如题
思路:
代码:
1 class Solution { 2 public List<Integer> findAnagrams(String s, String p) { 3 //corner case 4 List<Integer> res = new ArrayList<>(); 5 if (s == null || s.length() == 0 || p == null || p.length() == 0) return res; 6 // initialize 7 int left = 0; 8 int right = 0; 9 int count = p.length(); 10 int[] map = new int[256]; 11 // each char‘s frequency 12 for(int i = 0; i < p.length(); i++){ 13 map[p.charAt(i)]++; 14 } 15 16 // build window 17 while (right < s.length()){ 18 // this char exists in p 19 if (map[s.charAt(right)] > 0){ 20 count --; 21 } 22 map[s.charAt(right)] --; 23 // if the window size equals to p 24 // 如果此时左右指针的差值等于p的长度 25 if (right - left == p.length()-1){ 26 // find 1st res 27 if (count == 0) 28 // add the left index 29 res.add(left); 30 // move left pointer to start new search 31 // 如果当这个字符原来是p中的话,现在移动指针需要还原以前原有的matchSize,开始新的搜索 32 if (map[s.charAt(left)] >= 0) 33 matchSize ++; 34 // 还原以前每个元素减去的1 35 map[s.charAt(left)]++; 36 left++; 37 } 38 right++; 39 } 40 41 return res; 42 } 43 }
原文地址:https://www.cnblogs.com/liuliu5151/p/9810073.html
时间: 2024-10-11 05:00:05