add: 220202

This commit is contained in:
Lam Haoyin 2022-02-02 11:40:40 +08:00
parent ca2536a1f7
commit 5e1e7d81a4
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 40 additions and 1 deletions

39
2202/220202.cpp Normal file
View File

@ -0,0 +1,39 @@
#include <vector>
#include <string>
class Solution {
private:
template<int N>
static inline constexpr int alter(int n) {
return n ? -(n == N) : 1;
}
public:
static std::vector<int> findAnagrams(const std::string& s, const std::string& p) {
std::vector<int> ret;
int np = p.length(), ns = s.length();
int cnt[26]{};
for (char ch : p)
--cnt[ch - 'a'];
for (int i = std::min(np, ns); i--;)
++cnt[s[i] - 'a'];
// Interval: [L, R)
int C = std::count(cnt, cnt + 26, 0);
for (int L = 0, R = np; R < ns; ++L, ++R) {
if (26 == C)
ret.push_back(L);
C += alter<-1>(--cnt[s[L] - 'a']) + alter<1>(++cnt[s[R] - 'a']);
}
if (26 == std::count(cnt, cnt + 26, 0))
ret.push_back(ns - np);
return ret;
}
};
int main() {
auto ret = Solution::findAnagrams("cbaebabacd", "abc");
for (int i : ret)
std::printf("%d ", i);
return 0;
}

View File

@ -3,4 +3,4 @@ PROJECT(2202)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2202 220202-CN.cpp) ADD_EXECUTABLE(2202 220202.cpp)