一.問題描述
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