forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindAllAnagramsinaString.java
64 lines (48 loc) · 1.04 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
58
59
60
61
62
63
64
class Solution {
// TC : O(n)
// SC: O(n) "aaaaa" t="a"
public List<Integer> findAnagrams(String s, String t) {
List<Integer> ans = new ArrayList<>();
int unmatchingCharCount = t.length();
if(t.length()>s.length()){
return ans;
}
int[] freqCount = new int[26];
for(int i=0;i<t.length();i++){
int index = t.charAt(i)-'a';
freqCount[index]++;
}
int start =0;
int end =0;
for(;end<t.length();end++) {
int index = s.charAt(end)-'a';
if(freqCount[index]>0){
unmatchingCharCount--;
}
freqCount[index]--;
}
if(unmatchingCharCount==0){
ans.add(start);
}
for(;end<s.length();){
// remove starting index
int indexStart = s.charAt(start) -'a';
if(freqCount[indexStart]>=0) {
// char was present in t
unmatchingCharCount++;
}
freqCount[indexStart]++;
start++;
int indexEnd = s.charAt(end)-'a';
if(freqCount[indexEnd]>0){
unmatchingCharCount--;
}
freqCount[indexEnd]--;
end++;
if(unmatchingCharCount==0){
ans.add(start);
}
}
return ans;
}
}