From 5e1e7d81a43e7aef09c1631d554554d06bdc6c31 Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Wed, 2 Feb 2022 11:40:40 +0800 Subject: [PATCH] add: 220202 --- 2202/220202.cpp | 39 +++++++++++++++++++++++++++++++++++++++ 2202/CMakeLists.txt | 2 +- 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 2202/220202.cpp diff --git a/2202/220202.cpp b/2202/220202.cpp new file mode 100644 index 0000000..f00539e --- /dev/null +++ b/2202/220202.cpp @@ -0,0 +1,39 @@ +#include +#include + +class Solution { +private: + template + static inline constexpr int alter(int n) { + return n ? -(n == N) : 1; + } +public: + static std::vector findAnagrams(const std::string& s, const std::string& p) { + std::vector 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; +} diff --git a/2202/CMakeLists.txt b/2202/CMakeLists.txt index cb0e1e3..5b90e21 100644 --- a/2202/CMakeLists.txt +++ b/2202/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2202) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2202 220202-CN.cpp) +ADD_EXECUTABLE(2202 220202.cpp)