Skip to content

Commit 75d69cf

Browse files
Create Day 17 Find All Anagrams in a String.cpp
1 parent d88dd9e commit 75d69cf

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
PROBLEM:
2+
3+
4+
5+
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
6+
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
7+
The order of output does not matter.
8+
9+
Example 1:
10+
Input:
11+
s: "cbaebabacd" p: "abc"
12+
13+
Output:
14+
[0, 6]
15+
16+
Explanation:
17+
The substring with start index = 0 is "cba", which is an anagram of "abc".
18+
The substring with start index = 6 is "bac", which is an anagram of "abc".
19+
20+
Example 2:
21+
Input:
22+
s: "abab" p: "ab"
23+
24+
Output:
25+
[0, 1, 2]
26+
27+
Explanation:
28+
The substring with start index = 0 is "ab", which is an anagram of "ab".
29+
The substring with start index = 1 is "ba", which is an anagram of "ab".
30+
The substring with start index = 2 is "ab", which is an anagram of "ab".
31+
32+
33+
34+
35+
SOLUTION:
36+
37+
38+
class Solution {
39+
public:
40+
vector<int> findAnagrams(string s, string p) {
41+
42+
int i,j,n1,n2,f;
43+
n1=s.size();
44+
n2=p.size();
45+
46+
vector<int> p_map(26,0),s_map(26,0);
47+
vector<int> v;
48+
49+
if(n2>n1)
50+
return v;
51+
52+
for(i=0;i<n2;i++)
53+
{
54+
p_map[p[i]-'a']++;
55+
s_map[s[i]-'a']++;
56+
}
57+
58+
if(p_map==s_map) //Sliding Window
59+
v.push_back(0);
60+
61+
j=1;
62+
63+
for(i=n2;i<n1;i++)
64+
{
65+
s_map[s[i-n2]-'a']--;
66+
s_map[s[i]-'a']++;
67+
68+
if(s_map==p_map)
69+
v.push_back(j);
70+
71+
j++;
72+
}
73+
74+
return v;
75+
}
76+
};

0 commit comments

Comments
 (0)