|
| 1 | +package string; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Map; |
| 7 | + |
| 8 | +/* |
| 9 | +Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. |
| 10 | +
|
| 11 | +Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. |
| 12 | +
|
| 13 | +The order of output does not matter. |
| 14 | +
|
| 15 | +Example 1: |
| 16 | +
|
| 17 | +Input: |
| 18 | +s: "cbaebabacd" p: "abc" |
| 19 | +
|
| 20 | +Output: |
| 21 | +[0, 6] |
| 22 | +
|
| 23 | +Explanation: |
| 24 | +The substring with start index = 0 is "cba", which is an anagram of "abc". |
| 25 | +The substring with start index = 6 is "bac", which is an anagram of "abc". |
| 26 | +Example 2: |
| 27 | +
|
| 28 | +Input: |
| 29 | +s: "abab" p: "ab" |
| 30 | +
|
| 31 | +Output: |
| 32 | +[0, 1, 2] |
| 33 | +
|
| 34 | +Explanation: |
| 35 | +The substring with start index = 0 is "ab", which is an anagram of "ab". |
| 36 | +The substring with start index = 1 is "ba", which is an anagram of "ab". |
| 37 | +The substring with start index = 2 is "ab", which is an anagram of "ab". |
| 38 | + * */ |
| 39 | + |
| 40 | +public class FindAllAnagramsInAString |
| 41 | +{ |
| 42 | + public List<Integer> findAnagrams( String s, String p ) |
| 43 | + { |
| 44 | + List<Integer> result = new ArrayList<>(); |
| 45 | + Map<Character, Integer> currWind = new HashMap<>(); |
| 46 | + |
| 47 | + for ( Character ch : p.toCharArray() ) |
| 48 | + { |
| 49 | + currWind.put( ch, currWind.getOrDefault( ch, 0 ) + 1 ); |
| 50 | + } |
| 51 | + |
| 52 | + int match = 0; |
| 53 | + for ( int i = 0; i < s.length(); i++ ) |
| 54 | + { |
| 55 | + // add char |
| 56 | + char chToAdd = s.charAt( i ); |
| 57 | + if ( currWind.containsKey( chToAdd ) ) |
| 58 | + { |
| 59 | + currWind.put( chToAdd, currWind.get( chToAdd ) - 1 ); |
| 60 | + if ( currWind.get( chToAdd ) == 0 ) |
| 61 | + { |
| 62 | + match++; |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + // remove char |
| 67 | + if ( i >= p.length() ) |
| 68 | + { |
| 69 | + char chToRemove = s.charAt( i - p.length() ); |
| 70 | + if ( currWind.containsKey( chToRemove ) ) |
| 71 | + { |
| 72 | + currWind.put( chToRemove, currWind.get( chToRemove ) + 1 ); |
| 73 | + } |
| 74 | + if ( currWind.get( chToRemove ) == 1 ) |
| 75 | + { |
| 76 | + match--; |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + // verify match |
| 81 | + if ( match == currWind.size() ) |
| 82 | + { |
| 83 | + result.add( i - p.length() + 1 ); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + return result; |
| 88 | + } |
| 89 | +} |
0 commit comments