方法一、暴力方法
使用Python3内置index()
或find()
函数进行逻辑判断
str.index(), str.find()函数两者区别:
str.find(sub[, start[, end]])
返回子字符串 sub 在 s[start:end] 切片内被找到的最小索引。 可选参数 start 与 end 会被解读为切片表示法。 如果 sub 未被找到则返回 -1。
str.index(sub[, start[, end]])
类似于 find(),但在找不到子字符串时会引发 ValueError
Python3 代码题解
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not haystack and not needle:
return 0
if needle in haystack:
return haystack.index(needle)
else:
return -1
Source: LeetCode(The title reproduced in this blog is for personal study use only)