• Leetcode_28【实现strStr()】


    文章目录:

    • 题目
    • 脚本一
    • 脚本一逻辑

    题目:

    实现 strStr() 函数。

    给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。

    示例 1:

    输入: haystack = "hello", needle = "ll"
    输出: 2
    示例 2:

    输入: haystack = "aaaaa", needle = "bba"
    输出: -1
    说明:

    当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

    对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。


    脚本一:【用时:28ms】

    class Solution:
        def strStr(self, haystack: str, needle: str) -> int:
            try:
                bb = haystack.index(needle)
                return(bb)
            except ValueError:
                return(-1)

    脚本一逻辑:

    • 此脚本调用字符串的方法index(),但此方法遇到没有包含的短字符串时,会返回ValueError
    • 此时只需要调用try...except即可

    脚本二:【用时:52ms】

    class Solution:
        def strStr(self, haystack: str, needle: str) -> int:
            return(haystack.find(needle))

    脚本二逻辑:

    • 此字符串方法find,既能返回匹配的短字符串索引号
    • 也能在没有包含短字符串时,会返回-1值
  • 相关阅读:
    第六篇:python高级之网络编程
    第五篇:python高级之面向对象高级
    sublime插件开发教程
    Metatable In Lua 浅尝辄止
    cocos2dx-lua绑定之代码编辑器
    sublime入门文章
    Sublime Text快捷键
    lua中文教程【高级知识】
    lua基本语法
    Lua 不是 C++
  • 原文地址:https://www.cnblogs.com/mailong/p/12037883.html
Copyright © 2020-2023  润新知