题目描述:
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().
题目大意:
- 给定haystack,和needle两个字符串,查看needle是否为haystack的子字符串,是的话,返回所在位置的第一个元素的索引
- 题目有要求,如果不是子字符串,返回-1,如果needle为空,返回0
解题思路:
- 其实在写完题目大意时,已经将思路说出来了,依照题目要求,为空时,返回0,如果是子字符串,返回所在位置的对一个元素的索引
- 如果不是,返回-1
- 个人代码的思路是,增加了一个变量记录needle的长度,在haystack中遇到了和needle中第一个元素相等的元素的时候,需确定相等的那个元素,到底是不是needle中的那个元素,所以加上needle的字符串长度,判断一下是否相等,即可
- 见代码,一目了然
少废话,上代码:
class Solution:
def strStr(self, haystack, needle):
if not needle:
return 0
l = len(needle)
if needle in haystack:
for i in range(len(haystack)):
#首先要查找到子字符串needle的位置,然后相等的第一个字符的索引就是答案
#haystack[i:i+l] == needle需要设置此条语句,如果只有前面一句
#则可能会出现haystack="Hlello",needle="ll",此时返回值是1,是错的
if haystack[i] == needle[0] and haystack[i:i+l] == needle:
return i
else:
return -1
运行时间和内存占用:
- Runtime: 28 ms, faster than 76.38% of Python3 online submissions for Implement strStr().
- Memory Usage: 14 MB, less than 12.31% of Python3 online submissions for Implement strStr().