From f820cf2f8cc1628b1b04b09e745c59fc6b3a3ee6 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Tue, 15 Nov 2022 15:58:41 +0800 Subject: [PATCH] s0028 --- ...ex_of_the_first_occurrence_in_a_string.hpp | 13 +++++++++++++ ...ex_of_the_first_occurrence_in_a_string.cpp | 18 ++++++++++++++++++ ...ex_of_the_first_occurrence_in_a_string.cpp | 19 +++++++++++++++++++ 3 files changed, 50 insertions(+) create mode 100644 include/s0028_find_the_index_of_the_first_occurrence_in_a_string.hpp create mode 100644 src/s0028_find_the_index_of_the_first_occurrence_in_a_string.cpp create mode 100644 tests/s0028_find_the_index_of_the_first_occurrence_in_a_string.cpp diff --git a/include/s0028_find_the_index_of_the_first_occurrence_in_a_string.hpp b/include/s0028_find_the_index_of_the_first_occurrence_in_a_string.hpp new file mode 100644 index 0000000..5c3211b --- /dev/null +++ b/include/s0028_find_the_index_of_the_first_occurrence_in_a_string.hpp @@ -0,0 +1,13 @@ +#ifndef S0028_FIND_THE_INDEX_OF_THE_FIRST_OCCURRENCE_IN_A_STRING +#define S0028_FIND_THE_INDEX_OF_THE_FIRST_OCCURRENCE_IN_A_STRING + +#include + +using namespace std; + +class Solution { + public: + int strStr(string haystack, string needle); +}; + +#endif diff --git a/src/s0028_find_the_index_of_the_first_occurrence_in_a_string.cpp b/src/s0028_find_the_index_of_the_first_occurrence_in_a_string.cpp new file mode 100644 index 0000000..0617f6d --- /dev/null +++ b/src/s0028_find_the_index_of_the_first_occurrence_in_a_string.cpp @@ -0,0 +1,18 @@ +#include "s0028_find_the_index_of_the_first_occurrence_in_a_string.hpp" + +int Solution::strStr(string haystack, string needle) { + int haystackLen = haystack.length(); + int needleLen = needle.length(); + for (int i{0}; i < haystackLen; ++i) { + for (int j{0}, iTmp = i; j < needleLen; ++j) { + if (haystack[iTmp] != needle[j]) { + break; + } else if (j == needleLen - 1) { + return i; + } else { + ++iTmp; + } + } + } + return -1; +} diff --git a/tests/s0028_find_the_index_of_the_first_occurrence_in_a_string.cpp b/tests/s0028_find_the_index_of_the_first_occurrence_in_a_string.cpp new file mode 100644 index 0000000..6c83072 --- /dev/null +++ b/tests/s0028_find_the_index_of_the_first_occurrence_in_a_string.cpp @@ -0,0 +1,19 @@ +#include "s0028_find_the_index_of_the_first_occurrence_in_a_string.hpp" + +#include + +TEST(Problem28, Case1) { + string haystack{"sadbutsad"}; + string needle{"sad"}; + int o{0}; + Solution solution; + EXPECT_EQ(solution.strStr(haystack, needle), o); +} + +TEST(Problem28, Case2) { + string haystack{"leetcode"}; + string needle{"leeto"}; + int o{-1}; + Solution solution; + EXPECT_EQ(solution.strStr(haystack, needle), o); +}