28. Implement strStr()
easy
题目
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().
代码:
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle=="":
return 0
if needle in haystack:
return haystack.index(needle)
else:
return -1

本文介绍了一个简单的Python实现strStr()函数的方法。该函数用于返回子串在主串中首次出现的位置索引,若子串不存在则返回-1。特别地,当子串为空字符串时,按照C和Java的标准返回0。
512

被折叠的 条评论
为什么被折叠?



