From 755c0c28001f8cb21f9d0f3c543822f8d4c5a3bf Mon Sep 17 00:00:00 2001 From: Eatswap Date: Fri, 3 Mar 2023 19:09:47 +0800 Subject: [PATCH] add: 230303 --- cpp/2303/230303.cpp | 33 +++++++++++++++++++++++++++++++++ cpp/2303/CMakeLists.txt | 2 +- 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 cpp/2303/230303.cpp diff --git a/cpp/2303/230303.cpp b/cpp/2303/230303.cpp new file mode 100644 index 0000000..d762145 --- /dev/null +++ b/cpp/2303/230303.cpp @@ -0,0 +1,33 @@ +#include +#include +#include + +/** + * 28. Find the Index of the First Occurrence in a String + * + * Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. + */ + +class Solution { +public: + static int strStr(const std::string& s, const std::string& t) { + const int m = s.length(), n = t.length(); + std::vector p(n); + for (int i = 1; i < n; ++i) { + int j = p[i - 1]; + for (; j > 0 && t[i] != t[j]; j = p[j - 1]); + p[i] = j + (t[i] == t[j]); + } + for (int i = 0, j = 0; i < m; ++i) { + for (; j > 0 && s[i] != t[j]; j = p[j - 1]); + if (s[i] == t[j] && ++j >= n) + return i - j + 1; + } + return -1; + } +}; + +int main() { + std::cout << Solution::strStr("busasasasasapsadpp", "sasasasapsad"); + return 0; +} diff --git a/cpp/2303/CMakeLists.txt b/cpp/2303/CMakeLists.txt index ddc807a..3e5f772 100644 --- a/cpp/2303/CMakeLists.txt +++ b/cpp/2303/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2303) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2303 230302.cpp) +ADD_EXECUTABLE(2303 230303.cpp)