zoukankan      html  css  js  c++  java
  • 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方法的详细解释:菜鸟教程

  • 相关阅读:
    快速创建一个 Servlet 项目(1)
    快速创建一个 Servlet 项目(2)
    多级派生情况下派生类的构造函数
    最近看了点C++,分享一下我的进度吧!
    进程同步&进程间通信
    multiprocess模块
    进程
    网络编程之socket
    网络通信原理
    网络通信的流程 | 初始socket
  • 原文地址:https://www.cnblogs.com/tbgatgb/p/11112865.html
Copyright © 2011-2022 走看看