zoukankan      html  css  js  c++  java
  • LeetCode--028--实现strSTR()

    问题描述:

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

    示例 1:

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

    示例 2:

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

    方法1:直接用find方法

     1 class Solution(object):
     2     def strStr(self, haystack, needle):
     3         """
     4         :type haystack: str
     5         :type needle: str
     6         :rtype: int
     7         """
     8         index = haystack.find(needle)
     9         if index >= 0:
    10             return index
    11         else:
    12             return -1

    方法2:用截取靶串的方式做对比

     1 class Solution(object):
     2     def strStr(self, haystack, needle):
     3         """
     4         :type haystack: str
     5         :type needle: str
     6         :rtype: int
     7         """
     8         len1=len(haystack)
     9         len2=len(needle)
    10         for i in range(len1-len2+1):
    11             if haystack[i:i+len2]==needle:
    12                 return i
    13         return -1

     2018-07-23 18:10:11

  • 相关阅读:
    字典dict
    数组处理
    switch语句
    java基础复习2
    位运算
    内存中占用的字节
    java基础复习
    常用快捷键
    利用Typora设计博客的方式
    java数据结构-排序算法-堆算法
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/9356129.html
Copyright © 2011-2022 走看看