Table of Contents
一、中文版
實現 strStr() 函數。
給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。
示例 1:
輸入: haystack = "hello", needle = "ll"
輸出: 2
示例 2:
輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
說明:
當 needle 是空字符串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。
對於本題而言,當 needle 是空字符串時我們應當返回 0 。這與C語言的 strstr() 以及 Java的 indexOf() 定義相符。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/implement-strstr
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
二、英文版
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().
三、My answer
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
res = -1
if not haystack:
if not needle:
return 0
else:
return -1
for i in range(len(haystack)-len(needle)+1):
j = 0
while j in range(len(needle)):
if haystack[i+j] != needle[j]:
break
else:
j += 1
if j == len(needle):
res = i
return res
return res
四、解題報告
1、先對 haystack 和 needle 進行特判。
2、遍歷 haystack ,截止到最後一個能容下 needle 的位置即可。
3、在遍歷 haystack 的每一位時都往後看是否與 needle 相等。