题目描述:
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
我的解答:
class Solution:
def strStr(self, haystack, needle):
if needle == haystack or len(needle)<1:
return 0
for i in range(0 , len(haystack) - len(needle) + 1):
result = i
j = 0
while j < len(needle) and result < len(haystack) \
and haystack[result] == needle[j]:
result += 1
j += 1
if j == len(needle):
return i
return -1
参考答案:
class Solution(object):
def strStr(self, haystack, needle):
for i in range(len(haystack) - len(needle)+1):
if haystack[i:i+len(needle)] == needle:
return i
return -1
学习:
字符串的可以直接取出一段来比较haystack[i:i+len(needle)] == needle