力扣题目:实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
方法一:
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
# if needle not in haystack:
# return -1
# else:
# # str_hay = haystack.replace('k',needle)
# return haystack.index(needle)
return haystack.find(needle)
字符串的高级用法:
string.find(str,beg=0,end=len(string)) 检测str是否包含在string中,如果beg和end指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值(找到的第一个位置的索引值),否则返回-1
例如:
haystack = 'aabbaab' needle='ab' print(haystack.find(needle))
》》1
string.index(str,beg=0,end=len(string)) 跟find()方法一样,只不过如果str不在string中会报一个异常
例如:
haystack = 'aabbaab' needle='ab' print(haystack.index(needle))
》》1
方法二:通过循环移位,比较字符串是否存在相同的情况:指针i在第一个字符串中依次移位,判断i+n(n为第二个字符串长度)是否相等,进行逐一比较
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle or len(needle) == 0 :
return 0
n = len(needle)
i = 0
while i <= (len(haystack)-n): ##等于两个字符串长度相减时,移位完毕
if haystack[i:i+n] == needle: ##依次移位,判断i+n(n为第二个字符串长度)是否相等
return i
else:
i += 1
if i > (len(haystack)-n):
return -1
作者:yuyuyuyuyu-7
链接:https://leetcode-cn.com/problems/implement-strstr/solution/python3jian-dan-si-lu-zhi-zhen-izai-di-yi-ge-zi-fu/