LeetCode28. 实现 strStr()
1.题目
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
2.示例
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
3.思路
本来以为是考察KMP方法呢,不会啊,然后用到python里面就变会用函数就可以了。
4.代码
1.python简单方法
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
length1 = len(haystack)
length2 = len(needle)
c=-1
for i in range(length1-length2+1):
if haystack[i:i+length2]==needle:
c=i
break
return c
2.直接使用find方法
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
return haystack.find(needle)