leetcode28 python implements strStr()

Implement  the strStr()  function.

Given a haystack string and a needle string, find the first position (0-based) in the haystack string where the needle string occurs. Returns -1 if not present   .

Example 1:

Input: haystack = "hello", needle = "ll"
 Output: 2

Example 2:

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

python code

class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        len1 = len (haystack)
        len2=len(needle)
        for i in range(len1-len2+1):
            if haystack[i:i+len2]==needle:
                return i
        return -1
        



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325800739&siteId=291194637