LeetCode 438. Find All Anagrams in a String
原题链接在这里:https://leetcode.com/problems/find-all-anagrams-in-a-string/
题目:
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
Example 1:
Input: s: "cbaebabacd" p: "abc" Output: [0, 6] Explanation: The substring with start index = 0 is "cba", which is an anagram of "abc". The substring with start index = 6 is "bac", which is an anagram of "abc".
Example 2:
Input: s: "abab" p: "ab" Output: [0, 1, 2] Explanation: The substring with start index = 0 is "ab", which is an anagram of "ab". The substring with start index = 1 is "ba", which is an anagram of "ab". The substring with start index = 2 is "ab", which is an anagram of "ab".
题解:
先将p的所有char对应的map count++.
然后快慢指针维护一个sliding window. 右侧runner每次都移动,对应的char的count减1. 若是count减1之前大于0, 表示char在p中, sum--.
sum为0时就找到了anagram.
当window大小为p长度时,移动左侧walker, 对应char的count加1. 若是count加1之前不是负数,表示这个char在p中, sum++.
Time Complexity: O(n). n = s.length().
Space: O(1). 用到了map.
AC Java:
1 public class Solution { 2 public List<Integer> findAnagrams(String s, String p) { 3 List<Integer> res = new ArrayList<Integer>(); 4 if(s == null || p == null || s.length() == 0 || p.length() == 0){ 5 return res; 6 } 7 int [] map = new int[256]; 8 for(int i = 0; i<p.length(); i++){ 9 map[p.charAt(i)]++; 10 } 11 int walker = 0; 12 int runner = 0; 13 int sum = p.length(); 14 while(runner < s.length()){ 15 if(map[s.charAt(runner++)]-- > 0){ 16 //Move runner everytime. Decrease corresponding char count by 1 17 //If current char count is larger than 0, then this char is in p 18 sum--; 19 } 20 21 if(sum == 0) { 22 //Find anagram 23 res.add(walker); 24 } 25 26 if(runner-walker == p.length() && map[s.charAt(walker++)]++ >= 0){ 27 //If windows's size is already p.length(), move walker and increase corresponding char count by 1 28 //If count before increasing is not smaller than 0, this char is in p 29 sum++; 30 } 31 } 32 return res; 33 } 34 }