-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetTheAnagrams.java
More file actions
50 lines (40 loc) · 1.57 KB
/
GetTheAnagrams.java
File metadata and controls
50 lines (40 loc) · 1.57 KB
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
import java.util.ArrayList;
import java.util.HashMap;
public class GetTheAnagrams {
public static boolean isSame(HashMap<Character,Integer> TargetWindow, HashMap<Character,Integer> CurrentWindow ){
for (char key : TargetWindow.keySet()) {
if (!CurrentWindow.containsKey(key) || !CurrentWindow.get(key).equals(TargetWindow.get(key))) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String str1 = "forxxorfxdofr";
String str2 = "for";
ArrayList<String> ans = new ArrayList<>();
int windowSize = str2.length();
HashMap<Character, Integer> TargetWindow = new HashMap<>();
for(char ch: str2.toCharArray()){
TargetWindow.put(ch, TargetWindow.getOrDefault(ch,0)+1);
}
HashMap<Character,Integer> CurrentMap = new HashMap<>();
int i = 0;
for(int j=0;j<str1.length();j++){
char ch = str1.charAt(j);
CurrentMap.put(ch,CurrentMap.getOrDefault(ch,0)+1);
// System.out.println(CurrentMap);
if(j-i + 1> windowSize){ // window shrinking logic
CurrentMap.put(str1.charAt(i), CurrentMap.get(str1.charAt(i))-1);
i+=1;
}
if(j-i+1 == windowSize && isSame(TargetWindow, CurrentMap)){
ans.add(str1.substring(i,j+1));
}
}
System.out.println("\nThe anagrams in the str1 are: \n");
for(String a: ans){
System.out.println(a);
}
}
}