LeetCode算法题之28. Implement strStr()(easy)【Python3题解】

题目描述:
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

解题思路:

  1. 其实在写完题目大意时,已经将思路说出来了,依照题目要求,为空时,返回0,如果是子字符串,返回所在位置的对一个元素的索引
  2. 如果不是,返回-1
  3. 个人代码的思路是,增加了一个变量记录needle的长度,在haystack中遇到了和needle中第一个元素相等的元素的时候,需确定相等的那个元素,到底是不是needle中的那个元素,所以加上needle的字符串长度,判断一下是否相等,即可
  4. 见代码,一目了然

少废话,上代码:

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().
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值