topic
leetcode28. Implement strStr() to
implement strStr() function.
Given a haystack string and a needle string, find
the first position (starting from 0) where the needle string appears in the haystack string . If it does not exist, -1 is returned.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Explanation:
When needle is an empty string, what value should we return? This is a good question in an interview.
For this question, we should return 0 when needle is an empty string. This
is consistent with the definition of strstr() in C language and indexOf() in Java.
Code
// C
#include <string.h>
int strStr(char* haystack, char* needle) {
if (needle == "") {
return 0;
}
int haystack_len = strlen(haystack);
int needle_len= strlen(needle);
char* temp = needle;
for (int i = 0; i <= haystack_len - needle_len; ++i){
int j = i;
int k = 0;
while((k < needle_len) && (haystack[j] == needle[k])){
++j;
++k;
}
if (k == needle_len){
return i;
}
}
return -1;
}
// C++
#include <string>
using namespace std;
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.empty()) {
return 0;
}
auto it = haystack.find(needle);
if (it == string::npos) {
return -1;
} else {
return it;
}
}
};
test
#include <iostream>
int main() {
{
// C
char* haystack = "hello";
char* needle = "lo";
cout << strStr(haystack, needle) << endl;
}
{
// C++
string haystack = "hello";
string needle = "ll";
Solution s;
cout << s.strStr(haystack, needle);
}
cin.get();
return 0;
}
- result
3
2