File tree Expand file tree Collapse file tree 1 file changed +80
-0
lines changed
Expand file tree Collapse file tree 1 file changed +80
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+
3+ Given a string s and a non-empty string p, find all the start indices of p's
4+ anagrams in s.
5+
6+ Strings consists of lowercase English letters only and the length of both
7+ strings s and p will not be larger than 20,100.
8+
9+ The order of output does not matter.
10+
11+ Example 1:
12+
13+ Input:
14+ s: "cbaebabacd" p: "abc"
15+
16+ Output:
17+ [0, 6]
18+
19+ Explanation:
20+ The substring with start index = 0 is "cba", which is an anagram of "abc".
21+ The substring with start index = 6 is "bac", which is an anagram of "abc".
22+
23+ */
24+
25+ // solution
26+
27+ class Solution {
28+ public:
29+
30+ bool compare (char ar1[],char ar2[])
31+ {
32+ for (int i=0 ;i<256 ;i++)
33+ {
34+ if (ar1[i]!=ar2[i])return false ;
35+ }
36+ return true ;
37+ }
38+ vector<int > findAnagrams (string s, string p) {
39+ vector<int > res;
40+ int m = p.length ();
41+ int n = s.length ();
42+
43+ if (n==0 )return res;
44+ if (m > n)return res;
45+
46+
47+ // frequency of letters in pattern & s
48+ char countp[256 ] = {0 };
49+ char counts[256 ] = {0 };
50+ for (int i=0 ;i<m;i++)
51+ {
52+ countp[p[i]]++;
53+ counts[s[i]]++;
54+ }
55+
56+ // remaining characters of s
57+ // using sliding window
58+ for (int j=m;j<n;j++)
59+ {
60+ if (compare (countp,counts))
61+ {
62+ res.push_back (j-m);
63+ }
64+ counts[s[j]]++;
65+ counts[s[j-m]]--; // remove the first letter from the current window
66+ }
67+
68+
69+ // same thing for last window manually
70+ if (compare (countp,counts))
71+ {
72+ res.push_back (n-m);
73+ }
74+
75+ return res;
76+
77+ }
78+ };
79+
80+
You can’t perform that action at this time.
0 commit comments