Leetcode 28 实现 strStr()

2020-06-26  本文已影响0人  SunnyQjm

实现 strStr()

题目

实现 strStr() 函数。

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

说明:

解答

测试验证

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

        (knowledge)

        思路:
        1. 对于haystack中每个可能的字符,判断以它为起始的子串是否和needle相等;
        """
        if not needle:
            return 0
        for i in range(0, len(haystack) - len(needle) + 1):
            if haystack[i : i + len(needle)] == needle:
                return i
        return -1


if __name__ == '__main__':
    solution = Solution()
    print(solution.strStr("hello", "ll"), "= 2")
    print(solution.strStr("aaaaa", "bba"), "= -1")
    print(solution.strStr("aaaaa", ""), "= 0")
上一篇 下一篇

猜你喜欢

热点阅读