-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindAllAnagramsInAString.java
57 lines (45 loc) · 1.38 KB
/
FindAllAnagramsInAString.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.leetcode.algorithms.easy.string;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class FindAllAnagramsInAString {
public static void main(String...strings) {
// Input
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
String p = scanner.next();
List<Integer> result = findAnagrams(s, p);
Integer[] output = result.toArray(new Integer[result.size()]);
// Output
System.out.println(Arrays.toString(output));
scanner.close();
}
public static List<Integer> findAnagrams(String s, String p) {
List<Integer> result = new ArrayList<>();
// Get sum of p
char[] charsP = p.toCharArray();
int pSum = 0;
for(char charP : charsP) {
pSum += Character.getNumericValue(charP);
}
Arrays.sort(charsP);
for(int i = 0; i <= (s.length() - p.length()); i++) {
// Get sum of substring S and compare with sum of p
String subStringS = s.substring(i, i + p.length());
char[] charsS = subStringS.toCharArray();
int sSum = 0;
for(char charS : charsS) {
sSum += Character.getNumericValue(charS);
}
Arrays.sort(charsS);
// Check for anagram
String stringCharsS = Arrays.toString(charsS);
String stringCharsP = Arrays.toString(charsP);
if((pSum == sSum) && (stringCharsP.equals(stringCharsS))) {
result.add(i);
}
}
return result;
}
}