zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):双指针类:第28题:实现 strStr():实现 strStr() 函数。 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。

    题目:
    实现 strStr():实现 strStr() 函数。  给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。  
    思路:
    思路比较简单,暴力法。
    程序:
    class Solution:
        def strStr(self, haystack: str, needle: str) -> int:
            length1 = len(haystack)
            length2 = len(needle)
            if length2 == 0:
                return 0
            if length1 == 0:
                return -1
            if length1 < length2:
                return -1
            index = 0
            while index < (length1 - length2 + 1):
                if haystack[index] == needle[0]:
                    if haystack[index : index + length2] == needle[:]:
                        return index
                    else:
                        index += 1
                else:
                    index += 1
            return - 1
  • 相关阅读:
    【11平台天梯】【原理分析】11平台天梯原理分析
    2020年8月11日
    2020年8月10日
    2020年8月12日
    2020年8月9日
    2020年8月13日
    2020年8月8日
    2020年8月7日
    2020年8月6日
    2020年8月14日
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12829641.html
Copyright © 2011-2022 走看看