# [LeetCode] 28. Implement strStr() 实现strStr()函数

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2


Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1


Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.empty()) return 0;
int m = haystack.size(), n = needle.size();
if (m < n) return -1;
for (int i = 0; i <= m - n; ++i) {
int j = 0;
for (j = 0; j < n; ++j) {
if (haystack[i + j] != needle[j]) break;
}
if (j == n) return i;
}
return -1;
}
};

class Solution {
public:
int strStr(string haystack, string needle) {
for (int i = 0; ; ++i) {
for (int j = 0; ; ++j) {
if (j == needle.size()) return i;
if (i + j == haystack.size()) return -1;
if (needle[j] != haystack[i + j]) break;
}
}
return -1;
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/28

Shortest Palindrome

Repeated Substring Pattern

https://leetcode.com/problems/implement-strstr/

https://leetcode.com/problems/implement-strstr/discuss/12807/Elegant-Java-solution

https://leetcode.com/problems/implement-strstr/discuss/12956/C%2B%2B-Brute-Force-and-KMP

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2015-06-29 08:51  Grandyang  阅读(21229)  评论(2编辑  收藏  举报