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
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().
总体来说这道题还是非常简单的,主要是考察思维的一个细度,对特殊情况如空字符串的处理。
一开始没看到它的声明:即空字符串返回0,第一版直接出错。
后面意识到了改了一下。
方法基本都大同小异,遍历字符串,然后和needle对比一下看看是否一样。
方法的初衷应该是不希望大家用bulit-in函数的,用的话那就非常简单了。
一种就是根据needle对字符串进行split,然后返回第一个split的长度就好(如果needle在haystack里面的话).
另外一种就是自己动手实现,对每一个位置进行切片比较,可以直接比较每一位置上和它后面k(needle的长度)个位置一起的字符串是否和needle相等。
优化一下我是先判断第一位是否相等,相等了再比较整个的长度.
多加了一个if语句,但是我觉得如果needle是个很长的字符串的话,提升性能的效果应该比较明显,似乎leetcode测试集并没有很长,提升效果有限。
更多leetcode算法题解法: 专栏 leetcode算法从零到结束 或者 leetcode 解题目录 Python3 一步一步持续更新~
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle=="":return 0
m=len(needle)
for i in range(len(haystack)-m+1):
if haystack[i]!=needle[0]:continue
if haystack[i:i+m]==needle:return i
return -1