您的位置:首页 > 其它

Leedcode(初级算法-字符串7): 实现strStr()

2019-05-05 15:06 190 查看

实现 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() 定义相符。

解法

解法一是常规解法

class Solution:
def strStr(self, haystack: str, needle: str) -> int:
# return haystack.find(needle)
if needle == '':
return 0
for i in range(len(haystack)):
if needle[0] == haystack[i]:
if needle[:] == haystack[i:i+len(needle)]:
return i
return -1

解法二是用find函数:find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果指定范围内如果包含指定索引值,返回的是索引值在字符串中的起始位置。如果不包含索引值,返回-1。

class Solution:
def strStr(self, haystack: str, needle: str) -> int:
return haystack.find(needle)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: