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

[leetcode By Python]strStr

2018-01-28 14:46 423 查看
题目:

Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2


Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1


代码+调试:

class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
i = 0
while i<len(haystack)-len(needle)+1:
h,n = i,0
while n<len(needle) and haystack[h]==needle
:
h = h+1
n = n+1
if n == len(needle):
return i
i = i+1
else:
return -1

a = Solution()
print a.strStr('h','')
第一次提交时出现错误,是因为当haystack='x',needle='',我认为应该输出-1,但系统告诉正确答案是0。这是由于我对字符串的理解出现了一点问题
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: