您的位置:首页 > 编程语言 > Python开发

LeetCode 28. Implement strStr()

2016-10-20 10:25 399 查看
题目:

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题意:
给定2个字符串"needle"和"haystack",找出“needle”在"haystack"中出现的第一次位置,

否则返回-1

题解:

使用自带index()函数:

class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle not in haystack:
return -1
else:
return haystack.index(needle)

不使用内置函数:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
for i in range(len(haystack) - len(needle)+1):
if haystack[i:i+len(needle)] == needle:
return i
return -1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python leetcode