跳转至

28. Implement strStr()

Leetcode Two Pointers String

题目

[Easy]

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

中文题目

实现字符串子串匹配函数strStr()。如果字符串A是字符串B的子串,则返回A在B中首次出现的地址,否则返回-1。

实际应用中常用KMP算法,但是比较复杂。

思路

brute-force: 一一比对

def strStr(self, haystack, needle):
    if needle == "":
        return 0
    for i in range(len(haystack)-len(needle)+1):
        for j in range(len(needle)):
            if haystack[i+j] != needle[j]:
                break
            if j == len(needle)-1:
                return i
    return -1

也可借用python直接对比

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