28. Implement strStr()

Implement [strStr()](http://www.cplusplus.com/reference/cstring/strstr/).

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

**Example 1:**

1
2
Input: haystack = "hello", needle = "ll"
Output: 2
**Example 2:**
1
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()](http://www.cplusplus.com/reference/cstring/strstr/) and Java's [indexOf()](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String)). 思路:双循环遍历,即可。代码如下。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.size() == 0) return 0;
if (needle.size() > haystack.size()) return -1;

for (int i = 0; i < haystack.size() - needle.size() + 1; i++) {
int j = 0;
for (; j < needle.size(); j++) {
if ( haystack[i + j] != needle[j])
break;
}
if (j == needle.size()) return i;
}

return -1;
}
};
Res. Runtime: 4 ms, Ranking 99.97%. 加上控制输入输出的语句后,Runtime: 0 ms, Ranking 100%