• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

nunca

但行好事 莫问前程
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

LeetCode Easy: 28. Implement strStr()

一、题目

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

二、思路

首先我想到的就是python中特有的切片功能,遍历给定的 haystack ,然后与needle进行匹配,考虑鲁棒性当needle长度小于haystack的长度,返回-1.

三、代码

#coding:utf-8
def strStr(haystack, needle):
    """
    :type haystack: str
    :type needle: str
    :rtype: int
    """

    if len(needle)>len(haystack):
        return -1
    else:
        for i in range((len(haystack)-len(needle)+1)):
            if needle == haystack[i:i+len(needle):1]:
                print(i)
                return i
        return -1

if __name__ == '__main__':
    a = "hello"
    b = 'dl'
    strStr(a,b)

  

niasd

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢

posted on 2018-03-24 07:38  乐晓东随笔  阅读(133)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3