leetcode: 实现 strStr()

实现 strStr() 函数。

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

这一题的道理就遍历就好,只是需要考虑一下为空的情况

代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle == "":
return 0
for i in range(len(haystack) - len(needle) + 1):
for j in range(len(needle)):
if haystack[i+j] != needle[j]:
break
if j == len(needle) - 1:
return i

return -1

今天也很短= =,没得办法,还有作业的嘛