Leetcode题库——28.实现strStr()


@author: ZZQ
@software: PyCharm
@file: strStr.py
@time: 2018/11/6 20:04
要求:给定一个 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() 定义相符。

class Solution():
    def __init__(self):
        pass

    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        len_h = len(haystack)
        len_n = len(needle)
        if len_n == 0 or needle == "" :
            return 0
        if len_h == 0 or haystack == "" or len_n > len_h:
            return -1
        index_h = 0
        while index_h < len_h:
            temp_index = index_h
            first_index = index_h
            match_t = 0
            for i in range(len_n):
                if temp_index == len_h:
                    return -1
                if haystack[temp_index] != needle[i]:
                    break
                temp_index += 1
                match_t += 1
            if match_t == len_n:
                return first_index
            else:
                index_h += 1
        return -1

    def strStr2(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        len_h = len(haystack)
        len_n = len(needle)
        if len_n == 0 or needle == "":
               return 0
        if len_h == 0 or haystack == "" or len_n > len_h:
               return -1
        index_h = 0
        while index_h < len_h:
               temp_h = index_h
               index_n = 0
               while haystack[temp_h] == needle[index_n]:
                   temp_h += 1
                   index_n += 1
                   if index_n == len_n:
                       return index_h
                   if temp_h == len_h:
                       return -1
               index_h += 1
        return -1
原文地址:https://www.cnblogs.com/zzq-123456/p/9917948.html