-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpermutation-in-string.cpp
75 lines (63 loc) · 1.18 KB
/
permutation-in-string.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
// https://leetcode.com/problems/permutation-in-string/
class Solution
{
public:
bool checkInclusion(string s1, string s2)
{
int s1Length = s1.size();
int s2Length = s2.size();
if (s1Length > s2Length)
{
return false;
}
// <character ASCII value, count>
map<int, int> m1;
map<int, int> m2;
for (int i = 0; i < s1Length; i++)
{
m1[s1[i] - 'a']++;
m2[s2[i] - 'a']++;
}
int totalMatch = 0;
int totalChar = 26;
for (int i = 0; i < totalChar; i++)
{
if (m1[i] == m2[i])
{
totalMatch++;
}
}
// Sliding Window
int leftPointer = 0;
int mapIndex = 0;
for (int rightPointer = s1Length; rightPointer < s2Length; rightPointer++)
{
if (totalMatch == 26)
{
return true;
}
mapIndex = (s2[rightPointer] - 'a');
m2[mapIndex]++;
if (m1[mapIndex] == m2[mapIndex])
{
totalMatch++;
}
else if (m2[mapIndex] == (m1[mapIndex] + 1))
{
totalMatch--;
}
mapIndex = (s2[leftPointer] - 'a');
m2[mapIndex]--;
if (m1[mapIndex] == m2[mapIndex])
{
totalMatch++;
}
else if (m2[mapIndex] == (m1[mapIndex] - 1))
{
totalMatch--;
}
leftPointer++;
}
return (totalMatch == 26);
}
};