-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnagram substring search.txt
70 lines (59 loc) · 1.43 KB
/
Anagram substring search.txt
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
Anagram Substring Search
Given a string A and a string B.
Find and return the starting indices of the substrings of A which matches any of the anagrams of B.
Note: An anagram is a play on words created by rearranging the letters of the original word to make a new word or phrase
Input Format
The arguments given are string A and string B.
Output Format
Return the starting indices of the substrings of A which matches any of the anagrams of B.
Constraints
1 <= length of the string A,B <= 100000
length of string A > length of string B
'a' < = A[i] ,B[i] < ='z'
For Example
Input 1:
A = "BACDGABCDA"
B = "ABCD"
Output 1:
[0, 5, 6]
Input 2:
A = "AAABABAA"
B = "AABA"
Output 2:
[0, 1, 4]
vector<int> Solution::solve(string A, string B) {
int hash[256];
memset(hash,0,sizeof(hash));
int m=B.length();
for(int i=0;i<m;i++){
hash[B[i]]++;
}
vector<int> ans;
int i=0,j=0,n=A.length();
while(i<n){
if(hash[A[i]]>0){
hash[A[i]]--;
i++;
}
else{
if(i-j==B.length()){
ans.push_back(j);
hash[A[j]]++;
j++;
}
else{
if(i==j){
i++;
j++;
}
else{
hash[A[j]]++;
j++;
}
}
}
}
if(i-j==B.length())
ans.push_back(j);
return ans;
}