• 5-1


    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() 定义相符。

    My solution:

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

    分析:这是最容易想到的方法。用in来判断needle是否在haystack中,然后从haystack的第一个元素开始,不断地和needle比较,最终返回找到的第一个索引。

    还有更加简单的方法:利用字符串的find或index方法(这两种方法是等价的)。代码如下:

    index方法:

    class Solution(object):
        def strStr(self, haystack, needle):
            """
            :type haystack: str
            :type needle: str
            :rtype: int
            """
            if needle not in haystack:
                        return -1
            else:
                return haystack.index(needle)
    

    关于index方法的详细解释:菜鸟教程

    find方法:

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

    find方法只需要一行代码就可以解决问题。

    关于find方法的详细解释:菜鸟教程

  • 相关阅读:
    MySQL 5.6.9 RC 发布
    红薯 Java 8 的日期时间新用法
    Couchbase Server 2.0 发布,NoSQL 数据库
    Firefox OS 模拟器 1.0 发布
    Calculate Linux 13 Beta 1 发布
    敏捷测试的团队构成
    Node.js 0.8.16 发布(稳定版)
    JASocket 1.1.0 发布
    Samba 4.0 正式版发布,支持活动目录
    Seafile 1.3 发布,文件同步和协作平台
  • 原文地址:https://www.cnblogs.com/tbgatgb/p/11112865.html
Copyright © 2020-2023  润新知