實(shí)現(xiàn) strStr() 函數(shù)拳魁。
給定一個(gè) haystack 字符串和一個(gè) needle 字符串乘客,在 haystack 字符串中找出 needle 字符串出現(xiàn)的第一個(gè)位置 (從0開(kāi)始)狐血。如果不存在,則返回 -1易核。
示例 1:
輸入: haystack = "hello", needle = "ll"
輸出: 2
示例 2:
輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
說(shuō)明:
當(dāng) needle 是空字符串時(shí)匈织,我們應(yīng)當(dāng)返回什么值呢?這是一個(gè)在面試中很好的問(wèn)題牡直。
對(duì)于本題而言缀匕,當(dāng) needle 是空字符串時(shí)我們應(yīng)當(dāng)返回 0 。這與C語(yǔ)言的 strstr() 以及 Java的 indexOf() 定義相符碰逸。
思路
遍歷字符串乡小,如果當(dāng)前字符與needle字符串的第一個(gè)字符相同:haystack[i] == needle[0],就在haystack字符串中截取與needle字符串相同長(zhǎng)度的字符串與needle進(jìn)行比較饵史,如果相同(haystack[i:i+length2] == needle)則直接返回當(dāng)前字符的索引i
python3解法
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
length1 = len(haystack)
length2 = len(needle)
if length2 == 0: return 0
if length1 < length2 or length1 == 0: return -1
for i in range(length1 - length2 + 1):
if haystack[i] == needle[0]:
if haystack[i:i+length2] == needle:
return i
return -1
來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/implement-strstr
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有满钟。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán)胜榔,非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。