-
Notifications
You must be signed in to change notification settings - Fork 5
/
LC_438_FindAllAnagramsString.cpp
62 lines (48 loc) · 1.32 KB
/
LC_438_FindAllAnagramsString.cpp
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
/*
https://leetcode.com/problems/find-all-anagrams-in-a-string/
438. Find All Anagrams in a String
*/
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
int sl = s.length();
int pl = p.length();
if(sl<=0 || pl<=0 || pl>sl) return {};
vector<int> hash(26,0);
for(char c: p)
{
++hash[c-'a']; // store pattern char in hashtable
}
for(int i=0; i<pl; i++)
{
--hash[s[i]-'a'];
}
bool flag = true;
vector<int> ans;
//sliding window approach
for(int i=0; i< sl-pl; i++)
{
flag = true;
for(int k=0; k< hash.size(); k++)
{
if(hash[k] != 0)
flag =false;
}
if(flag)
ans.push_back(i);
//remove first character
// add next character
++hash[s[i]-'a'];
--hash[s[i+pl] - 'a'];
}
flag = true;
for(int k=0; k< hash.size(); k++)
{
if(hash[k] != 0)
flag =false;
}
if(flag)
ans.push_back(sl-pl);
return ans;
}//end
};