# 28. Implement strStr() 实现 strStr()

@TOC

## # 题目描述

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
``````

## # 解题方法

### # find函数

Python中，find()函数就是实现这个功能，如果找不到子串的话，返回-1.

``````class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
return haystack.find(needle)
``````

### # 遍历+切片

``````class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
M, N = len(haystack), len(needle)
for i in range(M - N + 1):
if haystack[i : i + N] == needle:
return i
return -1
``````

C++写法：

``````class Solution {
public:
int strStr(string haystack, string needle) {
int M = haystack.size();
int N = needle.size();
for (int i = 0; i < M - N + 1; i ++){
if (haystack.substr(i, N) == needle){
return i;
}
}
return -1;
}
};
``````

## # 日期

2018 年 2 月 4 日 2018 年 11 月 3 日 —— 雾霾的周六 2018 年 11 月 26 日 —— 11月最后一周！