• LeetCode小白菜笔记[10]:Implement strStr()


    LeetCode小白菜笔记[10]:Implement strStr()

    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

    简言之,就是把后一个子串(needle)从前一个字符串(haystack)中提取出来,返回其第一次出现的位置,若不存在则返回 -1 。

    代码比较简单,不过特殊情况比较坑。。。按照题目的意思,如果 needle 是空的,则返回 0 ,即认为在第一个位置找到了。改了好几次才通过。代码如下:

    class Solution(object):
        def strStr(self, haystack, needle):
            """
            :type haystack: str
            :type needle: str
            :rtype: int
            """
            if not needle:
                return 0
            if len(haystack) < len(needle):
                return -1
            if len(haystack) == len(needle):
                return int(haystack == needle) - 1
            for idx in range(len(haystack) - len(needle) + 1):
                if haystack[idx:idx+len(needle)] == needle:
                    return idx
            return -1

    结果如下:

    这里写图片描述

    discuss里面的代码更简洁:

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

    有些特殊情况的处理可以纳入一般情况。如 len(needle)=0 的情况,haystack[ i : i ] = ”,因此返回0,符合题意,而且len(needle)比len(haystack)大的情况,由于haystack[ i : i + len(needle) ]如果后面的停止位置超出范围,则会一直取到haystack最末元素。因此永远不会相等,故最后 return - 1 。

    总结:

    通过设计算法将特殊情况纳入到普通情况来判断可以使得代码更简洁。

    注意range和 [ i : j ] 的包含前项不包含后项的性质。

    THE END

  • 相关阅读:
    ES6新特性
    CSS + HTML 鼠标在图片上悬停时的显示文字,移走时文字消失
    APICloud closeToWin和closeWin的使用
    基于vue-cli配置移动端自适应
    Cookies,localStorage,sessionStorage,Web SQL Database(客户端)会话存储学习
    select标签默认选择选项
    MySQL数据库的配置
    jsp定义 ,JSON对象
    eclipse配置
    VS2017 C++编译时出现 "the windows sdk version for 8.1 was not found"解决办法(亲测有效)
  • 原文地址:https://www.cnblogs.com/morikokyuro/p/13256846.html
Copyright © 2020-2023  润新知