|
| 1 | +package by.andd3dfx.string; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.HashSet; |
| 6 | +import java.util.List; |
| 7 | +import java.util.Set; |
| 8 | + |
| 9 | +/** |
| 10 | + * <pre> |
| 11 | + * <a href="https://leetcode.com/problems/find-all-anagrams-in-a-string/">Task description</a> |
| 12 | + * |
| 13 | + * Given two strings s and p, return an array of all the start indices of p's in s. You may return the answer in any order. |
| 14 | + * |
| 15 | + * Example 1: |
| 16 | + * Input: s = "cbaebabacd", p = "abc" |
| 17 | + * Output: [0,6] |
| 18 | + * Explanation: |
| 19 | + * The substring with start index = 0 is "cba", which is an anagram of "abc". |
| 20 | + * The substring with start index = 6 is "bac", which is an anagram of "abc". |
| 21 | + * |
| 22 | + * Example 2: |
| 23 | + * Input: s = "abab", p = "ab" |
| 24 | + * Output: [0,1,2] |
| 25 | + * Explanation: |
| 26 | + * The substring with start index = 0 is "ab", which is an anagram of "ab". |
| 27 | + * The substring with start index = 1 is "ba", which is an anagram of "ab". |
| 28 | + * The substring with start index = 2 is "ab", which is an anagram of "ab". |
| 29 | + * </pre> |
| 30 | + */ |
| 31 | +public class FindAllAnagramsInAString { |
| 32 | + |
| 33 | + public static List<Integer> findAnagrams(String s, String p) { |
| 34 | + List<Integer> result = new ArrayList<>(); |
| 35 | + var normalizedP = normalize(p); |
| 36 | + |
| 37 | + Set<String> approvedStrings = new HashSet<>(); |
| 38 | + approvedStrings.add(normalizedP); |
| 39 | + for (var start = 0; start <= s.length() - p.length(); start++) { |
| 40 | + String candidate = s.substring(start, start + p.length()); |
| 41 | + |
| 42 | + if (approvedStrings.contains(candidate) || normalizedP.equals(normalize(candidate))) { |
| 43 | + approvedStrings.add(candidate); |
| 44 | + result.add(start); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + return result; |
| 49 | + } |
| 50 | + |
| 51 | + private static String normalize(String p) { |
| 52 | + var chars = p.toCharArray(); |
| 53 | + Arrays.sort(chars); |
| 54 | + return new String(chars); |
| 55 | + } |
| 56 | +} |
0 commit comments