-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLC_567_permutationInStrings.cpp
82 lines (65 loc) · 1.76 KB
/
LC_567_permutationInStrings.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
https://leetcode.com/problems/permutation-in-string/
567. Permutation in String
*/
class Solution {
public:
/*
bool checkInclusion(string s1, string s2) {
// sort(s1.begin(), s1.end());
// do
// {
// if(s2.find(s1)!=string::npos)
// return true;
// }while(next_permutation(s1.begin(), s1.end()));
// return false;
if(s2.size()< s1.size()) return false;
vector<int> freq(26, 0);
for(char c: s1)
freq[c-'a']++;
for(int i=0; i<s1.size(); i++)
freq[s2[i]-'a']--;
bool flag = true;
for(int x: freq)
if(x!=0)
{
flag = false;
}
if(flag) return flag;
for(int i=s1.size(); i<s2.size(); i++)
{
flag = true;
freq[s2[i-s1.size()]-'a']++;
freq[s2[i]-'a']--;
for(int x: freq)
if(x!=0)
{
flag = false;
}
if(flag) return flag;
}
return flag;
}
*/
bool checkInclusion(string s1, string s2) {
int m = s1.length();
int n = s2.length();
if(n<m) return false;
array<int, 26> s1cnt{0}, s2cnt{0};
for(int i=0; i<m; i++)
{
s1cnt[s1[i]-'a']++;
s2cnt[s2[i]-'a']++;
}
if(s1cnt == s2cnt)
return true;
for(int i=m; i<n; i++)
{
s2cnt[s2[i-m]-'a']--;
s2cnt[s2[i]-'a']++;
if(s1cnt == s2cnt)
return true;
}
return false;
}
};