leetcode with python:28. Implement strStr()

题目:

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

For the purpose of this problem, we will return 0 when needle is an empty string.

给定两个字串(haystack,needle),检查needle是否在haystack内,若有回传needle第一次出现时的index,若无则回传-1,若needle为空,回传0

用一些字串操作,这题会变得十分简单

class Solution:    def strStr(self, haystack: str, needle: str) -> int:        if needle not in haystack:            return -1                    if needle=="":            return 0                    haystack=haystack.replace(needle," ")        for i in range(len(haystack)):            if haystack[i]==" ":                return i

先检测needle是否在haystack内及needle是否为空字串
确定needle在haystack内后将needle replace成" "
最后再检索" "的位置即可
最后执行时间为28ms(faster than 96.18%)

但这样似乎有点偷吃步
在讨论区有看到比较正规的解法

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

简单来说就是偏暴力解,一个一个去对比
不过最后执行时间为31ms(faster than 91.34%),也不算太差
大概分享一下其他写法

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章