LeetCode专题-Python实现之第28题: Implement strStr()

导航页-LeetCode专题-Python实现

相关代码已经上传到github:https://github.com/exploitht/leetcode-python
文中代码为了不动官网提供的初始几行代码内容,有一些不规范的地方,比如函数名大小写问题等等;更合理的代码实现参考我的github repo

1、读题

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

这道题看着有点无语,寻找大字符串里的小字符串,找不到返回-1,这不就是大python里的find()吗?于是我厚着脸皮写出了第一个版本的代码。

2、解题

如下代码,只有一行功能代码不是最屌的地方,最屌的时候提交后发现超过了99.86%的解决方案。忙活半天还不如调用一下自带的字符串处理函数嘛。

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        return haystack.find(needle)

3、符合出题人意图的解法

虽然上面一种方式也找不到啥毛病,不过这样做就不需要动脑了,还是手动实现一下这个find吧。
最先想到的是遍历大字符串,找到和小字符串开头相同的字符,则判断大字符串切片出来的小字符串长度的子串和小字符串是否相等。这样虽然效率不高,逻辑却很简单,先给出代码:

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not needle:
            return 0
        needle_len = len(needle)
        needle_start = needle[0]
        for index, value in enumerate(haystack):
            if value == needle_start:
                if haystack[index:needle_len + index] == needle:
                    return index
        return -1

4、第一次优化

代码解析过几天补充

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        # return haystack.find(needle)
        for i in range(len(haystack) + 1):
            for j in range(len(needle) + 1):
                if j == len(needle):
                    return i
                if i + j == len(haystack):
                    return -1
                if needle[j] != haystack[i + j]:
                    break

转载于:https://www.cnblogs.com/cloudgeek/p/7661929.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值