This commit is contained in:
Sainnhe Park 2022-11-15 15:58:41 +08:00
parent 381117a18a
commit f820cf2f8c
3 changed files with 50 additions and 0 deletions

View File

@ -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 <string>
using namespace std;
class Solution {
public:
int strStr(string haystack, string needle);
};
#endif

View File

@ -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;
}

View File

@ -0,0 +1,19 @@
#include "s0028_find_the_index_of_the_first_occurrence_in_a_string.hpp"
#include <gtest/gtest.h>
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);
}