567. Permutation in String
https://leetcode.com/problems/permutation-in-string/description/
Thoughts
Code
/*
* @lc app=leetcode id=567 lang=cpp
*
* [567] Permutation in String
*/
// @lc code=start
class Solution {
public:
bool checkInclusion(string s1, string s2) {
const int M = s1.length(), N = s2.length();
if (M > N) return false;
vector<int> freq(26, 0);
for (const auto c : s1) --freq[c - 'a'];
int cnt = 0;
for (int i = 0; i < M; ++i) {
const auto k = s2[i] - 'a';
++freq[k];
if (freq[k] <= 0) ++cnt;
}
if (cnt == M) return true;
for (int l = 0, r = M; r < N; ++r, ++l) {
++freq[s2[r] - 'a'];
if (freq[s2[r] - 'a'] <= 0) ++cnt;
if (freq[s2[l] - 'a'] <= 0) --cnt;
--freq[s2[l] - 'a'];
if (cnt == M) return true;
}
return false;
}
};
// @lc code=end
Analysis
Last updated