-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathAnagramSearch.java
More file actions
103 lines (83 loc) · 2.04 KB
/
AnagramSearch.java
File metadata and controls
103 lines (83 loc) · 2.04 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package questions.virendra;
import java.util.HashMap;
import java.util.HashSet;
public class AnagramSearch {
public static boolean foundAnagram(HashMap<Integer,Integer> patternHash, HashMap<Integer,Integer> textHash)
{
for(Integer key: patternHash.keySet())
{
if(textHash.containsKey(key))
{
if(textHash.get(key) != patternHash.get(key))
return false;
}
else return false;
}
return true;
}
public static boolean anagramSubstringSearch(String pattern, String text)
{
HashMap<Integer,Integer> patternHash = new HashMap<Integer,Integer>();
HashMap<Integer,Integer> textHash = new HashMap<Integer,Integer>();
for(int i=0; i<pattern.length();i++)
{
int patCh = (int)pattern.charAt(i);
int txtCh = (int)text.charAt(i);
if(!patternHash.containsKey(patCh))
{
patternHash.put(patCh, 1);
}
else
{
int temp = patternHash.get(patCh);
patternHash.put(patCh, ++temp);
}
if(!textHash.containsKey(txtCh))
{
textHash.put(txtCh, 1);
}
else
{
int temp = textHash.get(txtCh);
textHash.put(txtCh, ++temp);
}
}
int windowStart = 0;
int windowEnd = pattern.length()-1;
while(true)
{
if(foundAnagram(patternHash, textHash))
{
return true;
}
windowStart++;
windowEnd++;
if(windowEnd >= text.length())
return false;
int txtCh = (int)text.charAt(windowStart -1);
if(textHash.containsKey(txtCh))
{
int count = textHash.get(txtCh);
if(count==1)
textHash.remove(txtCh);
else
textHash.put(txtCh, count-1);
}
txtCh = (int)text.charAt(windowEnd);
if(!textHash.containsKey(txtCh))
{
textHash.put(txtCh, 1);
}
else
{
int temp = textHash.get(txtCh);
textHash.put(txtCh, ++temp);
}
}
}
public static void main(String args[])
{
AnagramSearch object = new AnagramSearch();
System.out.println(anagramSubstringSearch("xyiz", "afdgzyxksldfm"));
}
}