Skip to content

Commit 765d972

Browse files
author
Danieldu
committed
optimize 567
1 parent 234a608 commit 765d972

File tree

2 files changed

+60
-36
lines changed

2 files changed

+60
-36
lines changed

150/567.permutation-in-string.cpp

Lines changed: 0 additions & 36 deletions
This file was deleted.
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
* @lc app=leetcode id=567 lang=cpp
3+
*
4+
* [567] Permutation in String
5+
*/
6+
7+
// @lc code=start
8+
#include "bits/stdc++.h"
9+
using namespace std;
10+
11+
class Solution {
12+
public:
13+
bool checkInclusion(string s1, string s2) {
14+
int n1 = s1.size(), n2 = s2.size();
15+
if (n1 > n2) return false;
16+
vector<int> countS1(26, 0), countWin(26, 0);
17+
18+
for (char c: s1) {
19+
countS1[c - 'a']++;
20+
}
21+
22+
for (int i = 0; i < n1; i++) {
23+
countWin[s2[i] - 'a']++;
24+
}
25+
26+
int matchCount = 0;
27+
for (int i = 0; i < 26; i++) {
28+
if (countS1[i] == countWin[i]) {
29+
matchCount++;
30+
}
31+
}
32+
33+
if (matchCount == 26) return true;
34+
35+
for (int i = n1; i < n2; i++) {
36+
int newChar = s2[i] - 'a';
37+
int oldChar = s2[i - n1] - 'a';
38+
39+
if (countS1[oldChar] == countWin[oldChar]) {
40+
matchCount--;
41+
}
42+
countWin[oldChar]--;
43+
if (countS1[oldChar] == countWin[oldChar]) {
44+
matchCount++;
45+
}
46+
47+
if (countS1[newChar] == countWin[newChar]) {
48+
matchCount--;
49+
}
50+
countWin[newChar]++;
51+
if (countS1[newChar] == countWin[newChar]) {
52+
matchCount++;
53+
}
54+
if (matchCount == 26) return true;
55+
}
56+
return false;
57+
}
58+
};
59+
// @lc code=end
60+

0 commit comments

Comments
 (0)