Implement strStr().

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

思路

找出haystack字符串中,needle字符串第一次出现的索引号。

利用两层循环可以得到想要的结果,因为题目难度所限,对于O(n*m)的时间复杂度也没有报超时错误。

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
26
27
28
29
30
31
32
33
34
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
length = len(haystack)
lenned = len(needle)
if (length == lenned and length == 0):
return 0
if (length < lenned):
return -1
else:
for i in range(length):
flag = 1
pos = i
# 超出范围,needle不在haystack里
if (pos + lenned > length):
flag = 0
break
# 判断needle是不是真的在haystack里
for j in needle:
if (haystack[pos] != j):
flag = 0
break
pos += 1
# 返回对应的字符串索引
if (flag):
return i
return -1