Find All Anagrams in a String

时间:2022-04-11 19:27:21

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".

 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         Map<Character, Integer> map = new HashMap<>();
 8         for (int i = 0; i < t.length(); i++) {
 9             char ch = t.charAt(i);
10             map.put(ch, map.getOrDefault(ch, 0) + 1);
11         }
12         int begin = 0, end = 0;
13         int counter = t.length();
14         while (end < s.length()) {
15             char endChar = s.charAt(end);
16             if (map.containsKey(endChar)) {
17                 if (map.get(endChar) > 0) {
18                     counter--;
19                 }
20                 map.put(endChar, map.get(endChar) - 1);
21             }
22             end++;
23 
24             while (counter == 0) {
25                 if (end - begin == t.length()) {
26                     result.add(begin);
27                 }
28                 char beginChar = s.charAt(begin);
29                 if (map.containsKey(beginChar)) {
30                     map.put(beginChar, map.get(beginChar) + 1);
31                     if (map.get(beginChar) > 0) {
32                         counter++;
33                     }
34                 }
35                 begin++;
36             }
37         }
38         return result;
39     }
40 }