-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathlc438.java
More file actions
58 lines (58 loc) · 1.63 KB
/
Copy pathlc438.java
File metadata and controls
58 lines (58 loc) · 1.63 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
class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> ans = new ArrayList<Integer>();
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for(char c : p.toCharArray())
{
if(!map.containsKey(c))
{
map.put(c,0);
}
map.put(c,map.get(c)+1);
}
HashMap<Character, Integer> smap = new HashMap<Character, Integer>();
for(int i=0;i<s.length();i++)
{
if(!smap.containsKey(s.charAt(i)))
{
smap.put(s.charAt(i),1);
}
else
{
smap.put(s.charAt(i),map.get(s.charAt(i))+1);
}
if(i>=p.length()-1)
{
if(CheckIfMapsAreEqual(map, smap))
{
ans.add(i-p.length()+1);
}
char ch = s.charAt(i-p.length()+1);
int val = smap.get(ch);
smap.put(ch,val-1);
if(smap.get(ch)==0)
{
smap.remove(ch);
}
}
}
return ans;
}
private boolean CheckIfMapsAreEqual(HashMap<Character, Integer> a, HashMap<Character, Integer> b)
{
if(a.size() != b.size())
return false;
for(char c: a.keySet())
{
if(b.containsKey(c) && a.get(c) ==b.get(c))
{
//we are good
}
else
{
return false;
}
}
return true;
}
}