LeetCode:实现strStr()(Python版本)

LeetCode刷题日记

  • 实现strStr()
    • Python代码

实现strStr()

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/

实现 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() 定义相符。

Python代码

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        # return haystack.find(needle)

        if not needle:  # 判断needle为空的情况
            return 0
        if len(haystack) == 0 or len(haystack) < len(needle):  # 如果haystack为空或者needle比haystack长的情形
            return -1
        for i in range(len(haystack)):
            if haystack[i] == needle[0]:  # 如果首字符匹配,那么按照needle的长度来对haystack进行切片
                temp = haystack[i:i + len(needle)]
                flag = i
                if len(temp) == len(needle):  # 如果切片长度与needle长度相等,那么接着判断字符是否相同
                    for j in range(len(temp)):
                        if temp[j] == needle[j]:
                            if j == len(temp) - 1:
                                return flag
                            continue
                        else:
                            break
                else:  # 长度不等的情况,或者字符出现不同
                    if i == len(haystack) - 1:  # 如果haystack已经到了结尾
                        return -1
                    continue
            if i == len(haystack) - 1:  # 如果haystack已经到了结尾
                return -1

但是我发现。。Python中提供了字符串find()函数,我觉得题目应该是要自己实现,所以还是老老实实的做了普通的答案,一开始思路跑偏,用快慢指针判断,但是出现了错误,后来想到用切片应该可以做。
下面粘上更简洁的代码。。。。

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        return haystack.find(needle)

感觉站在了巨人的肩膀上。。。。

你可能感兴趣的:(字符串,Python,初级算法)