实现 strStr()

正则表达式法(速度慢):

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        import re
        result = re.search(needle, haystack)
        if result != None:
            return result.span()[0]
        else:
            return -1

find速度快:

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        return haystack.find(needle)

手写的(比正则表达式快):

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        len_h = len(haystack)
        len_n = len(needle)
        if len_n == 0 or (len_h == 0 and len_n == 0):
            return 0

        if len_h == 0:
            return -1
        
        for i in range(len_h):
            j = 0
            try:
                while (haystack[i + j] == needle[j]):
                    if j == len_n - 1:
                        return i
                    j += 1
                    
            except IndexError:
                return -1
        return -1

index没有find快:

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        try:
            return haystack.index(needle)
        except:
            return -1

 

你可能感兴趣的:(力扣刷题集锦)