• python 练习题 28. 实现 strStr()


    地址:https://leetcode-cn.com/problems/implement-strstr/

     1 '''
     2 实现 strStr() 函数。
     3 
     4 给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回  -1 。
     5 
     6  
     7 
     8 说明:
     9 
    10 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
    11 
    12 对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。
    13 
    14  
    15 
    16 示例 1:
    17 
    18 输入:haystack = "hello", needle = "ll"
    19 输出:2
    20 示例 2:
    21 
    22 输入:haystack = "aaaaa", needle = "bba"
    23 输出:-1
    24 示例 3:
    25 
    26 输入:haystack = "", needle = ""
    27 输出:0
    28 
    29 
    30 '''
    31 
    32 '''
    33 取haystack中长度和needle相同的值与needle判断,如果相等返回下标位置,不相等返回-1
    34 '''
    35 
    36 
    37 class Solution:
    38     def strStr(self, haystack: str, needle: str) -> int:
    39         numHay = len(haystack)
    40         numNee = len(needle)
    41         if numNee ==0 :return 0
    42         elif numHay ==0 :return -1
    43         res = -1
    44         for i in range(len(haystack)):
    45             if haystack[i:len(needle)+i]==needle:
    46                 res = i
    47                 break
    48         return res

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/implement-strstr
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  • 相关阅读:
    “中国半导体教父”张汝京:中国半导体只缺人才
    集群搭建
    Scrapy
    商品建模
    python wordcloud
    StaticFileMiddleware中间件如何处理针对文件请求
    Docker / CI / CD
    NET Memory Profiler 跟踪.net 应用内存
    SOS.dll (SOS Debugging Extension)
    Download the WDK, WinDbg, and associated tools
  • 原文地址:https://www.cnblogs.com/whycai/p/16187401.html
Copyright © 2020-2023  润新知