# 实现 strStr()

实现 strStr() 函数。

给你两个字符串 haystackneedle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回  -1

 

说明:

当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。

 

示例 1:

输入:haystack = "hello", needle = "ll"
输出:
2

示例 2:

输入:haystack = "aaaaa", needle = "bba"
输出:
-1

示例 3:

输入:haystack = "", needle = ""
输出:
0

 

提示:

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp int main() { Solution sol; int res; res = sol.strStr("hello", "ll"); cout << res; return 0; } ``` ## 答案 ```cpp class Solution { public: int strStr(string haystack, string needle) { return haystack.find(needle); } }; ``` ## 选项 ### A ```cpp class Solution { public: int strStr(string haystack, string needle) { int l1 = haystack.size(); int l2 = needle.size(); int i = 0, j = 0; while (i < l1 && j < l2) { if (haystack[i] == needle[j]) { i++; j++; } else { i = i - j + 1; j = 0; } } if (j >= l2) return (i - j); else return -1; } }; ``` ### B ```cpp class Solution { public: vector next(string str) { vector v; v.push_back(-1); int i = 0, j = -1; while (i < str.size()) { if (j == -1 || str[i] == str[j]) { ++i; ++j; v.push_back(j); } else j = v[j]; } return v; } int strStr(string haystack, string needle) { int i = 0; int j = 0; int len1 = haystack.size(), len2 = needle.size(); vector nextptr; if (needle.empty()) return 0; nextptr = next(needle); while ((i < len1) && (j < len2)) { if ((j == -1) || (haystack[i] == needle[j])) { i++; j++; } else { j = nextptr[j]; } } if (j == needle.size()) return i - j; else return -1; } }; ``` ### C ```cpp class Solution { public: int strStr(string haystack, string needle) { int flag = 0; int i, j; int sizeofh = haystack.length(); int sizeofn = needle.length(); if (needle == "") { return 0; } for (i = 0; i < sizeofh; i++) { for (j = 0; j < sizeofn; j++) { if (i + j > sizeofh) { break; } if (haystack[i + j] != needle[j]) { break; } } } if (flag) { return i; } else return -1; } }; ```