题目:
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[n]:
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。这是由于我对字符串的理解出现了一点问题