Skip to content

Commit 57fa43f

Browse files
committed
Add solution of FindAllAnagramsInAString task
1 parent dfa9b2b commit 57fa43f

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package by.andd3dfx.string;
2+
3+
import org.junit.Test;
4+
5+
import java.util.List;
6+
7+
import static by.andd3dfx.string.FindAllAnagramsInAString.findAnagrams;
8+
import static org.assertj.core.api.Assertions.assertThat;
9+
10+
public class FindAllAnagramsInAStringTest {
11+
12+
@Test
13+
public void testFindAnagrams() {
14+
assertThat(findAnagrams("cbaebabacd", "abc")).isEqualTo(List.of(0, 6));
15+
assertThat(findAnagrams("abab", "ab")).isEqualTo(List.of(0, 1, 2));
16+
assertThat(findAnagrams("abcabc", "cz")).isEqualTo(List.of());
17+
}
18+
}

0 commit comments

Comments
 (0)