Skip to content

Commit e0e5cf9

Browse files
authored
Create 567. Permutation in String (#605)
2 parents 1ceb243 + c3a8aaf commit e0e5cf9

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

567. Permutation in String

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
class Solution {
2+
public:
3+
bool check(vector<int>& v1, vector<int>& v2) {
4+
// Compare the two frequency arrays
5+
for (int i = 0; i < 26; i++) {
6+
if (v1[i] != v2[i]) {
7+
return false;
8+
}
9+
}
10+
return true;
11+
}
12+
13+
bool checkInclusion(string s1, string s2) {
14+
// If s1 is longer than s2, it can't be a substring
15+
if (s1.size() > s2.size()) {
16+
return false;
17+
}
18+
19+
// Frequency count of characters in s1 and initial window of s2
20+
vector<int> cs1(26, 0);
21+
vector<int> cs2(26, 0);
22+
int n1 = s1.size();
23+
int n2 = s2.size();
24+
25+
// Count frequencies in s1 and first window of s2
26+
for (int i = 0; i < n1; i++) {
27+
cs1[s1[i] - 'a']++;
28+
cs2[s2[i] - 'a']++;
29+
}
30+
31+
// Check if the first window is a valid permutation
32+
if (check(cs1, cs2)) {
33+
return true;
34+
}
35+
36+
// Sliding window over s2
37+
for (int i = n1; i < n2; i++) {
38+
// Remove the character that goes out of the window
39+
cs2[s2[i - n1] - 'a']--;
40+
// Add the character that enters the window
41+
cs2[s2[i] - 'a']++;
42+
43+
// Check if the current window is a valid permutation
44+
if (check(cs1, cs2)) {
45+
return true;
46+
}
47+
}
48+
49+
// No valid permutation found
50+
return false;
51+
}
52+
};

0 commit comments

Comments
 (0)