diff --git a/cpp/2203/220316.cpp b/cpp/2203/220316.cpp new file mode 100644 index 0000000..cca0386 --- /dev/null +++ b/cpp/2203/220316.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +#include + +class Solution { +public: + static bool validateStackSequences(const std::vector& pushed, const std::vector& popped) { + const int n = pushed.size(); + + std::unordered_map m; + for (int i = 0; i < n; ++i) + m[pushed[i]] = i; + + std::vector processed(n); + for (int i = 0; i < n; ++i) + processed[i] = m[popped[i]]; + + int currentPushed = -1; + std::stack s; + for (int i = 0; i < n; ++i) { + if (processed[i] > currentPushed) { + // == Push to current, and pop current immediately + for (++currentPushed; currentPushed < processed[i]; ++currentPushed) { + s.push(currentPushed); + } + } else { + if (s.empty() || s.top() != processed[i]) + return false; + s.pop(); + } + } + return true; + } +}; + +int main() { + std::cout << Solution::validateStackSequences({1,2,3,4,5}, {1,2,3,4,5}); + return 0; +} diff --git a/cpp/2203/CMakeLists.txt b/cpp/2203/CMakeLists.txt index c52f182..c5b6d19 100644 --- a/cpp/2203/CMakeLists.txt +++ b/cpp/2203/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2203) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2203 220315.cpp) +ADD_EXECUTABLE(2203 220316.cpp)