438. 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".
分析:
这题和mininum window几乎一摸一样,使用两个pointer来找这样的window。
 1 public class Solution {
 2     public List<Integer> findAnagrams(String s, String t) {
 3         List<Integer> result = new LinkedList<>();
 4         if (t.length() > s.length()) {
 5             return result;
 6         }
 7 
 8         // get count of each letter
 9         Map<Character, Integer> map = new HashMap<>();
10         for (int i = 0; i < t.length(); i++) {
11             char ch = t.charAt(i);
12             map.put(ch, map.getOrDefault(ch, 0) + 1);
13         }
14         
15         int begin = 0, end = 0;
16         int counter = t.length();
17         while (end < s.length()) {
18             char endChar = s.charAt(end);
19             if (map.containsKey(endChar)) {
20                 if (map.get(endChar) > 0) {
21                     counter--;
22                 }
23                 map.put(endChar, map.get(endChar) - 1);
24             }
25             end++;
26 
27             while (counter == 0) {
28                 if (end - begin == t.length()) {
29                     result.add(begin);
30                 }
31                 char beginChar = s.charAt(begin);
32                 if (map.containsKey(beginChar)) {
33                     map.put(beginChar, map.get(beginChar) + 1);
34                     if (map.get(beginChar) > 0) {
35                         counter++;
36                     }
37                 }
38                 begin++;
39             }
40         }
41         return result;
42     }
43 }

 

posted @ 2019-04-28 11:21  北叶青藤  阅读(144)  评论(0编辑  收藏  举报