28. Implement strStr()

960次阅读
没有评论
Implement strStr().

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

Example 1:

<strong>Input:</strong> haystack = "hello", needle = "ll"
<strong>Output:</strong> 2

Example 2:

<strong>Input:</strong> haystack = "aaaaa", needle = "bba"
<strong>Output:</strong> -1

解法

class Solution:
    def strStr(self, haystack: 'str', needle: 'str') -> 'int':
        if len(needle)<1:
            return 0
        length=len(needle)
        for x in range(len(haystack)-length+1):
            if haystack[x:x+length]==needle:
                return x
        return -1
            
admin
版权声明:本站原创文章,由admin2019-02-11发表,共计290字。
转载提示:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)