Implement strStr().

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

Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

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

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

Example 3:
Input: haystack = "", needle = ""
Output: 0

Constraints:

  • 0 <= haystack.length, needle.length <= 5 * 10^4
  • haystack and needle consist of only lower-case English characters.

Solution in python:

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if len(needle) == 0:
            return 0
        len1 = len(haystack)
        len2 = len(needle)
        i = 0
        # L1-L2 make it be accepted
        while i < len1-len2 + 1:
            k = i
            j = 0
            while j < len2:
                if k < len1 and haystack[k] == needle[j]:
                    k += 1
                    j += 1
                else:
                    break
            if j == len2:
                return i
            i += 1

        return -1
最后修改日期: 2020年12月29日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。