[LeetCode]28 实现strStr()

题目描述

实现 strStr() 函数。

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

示例1:

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

示例2:

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

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle=='':
return 0

l = len(needle)
L = len(haystack)
if l > L: return -1
for i in range(L-l+1):
if haystack[i] == needle[0]:
tag=1
for j in range(l):
if haystack[i+j] != needle[j]:
tag=0
break
if tag:
return i
else:
pass
return -1