LeetCode小白菜笔记[10]:Implement strStr()

来源:互联网 发布:理查德杰弗森生涯数据 编辑:程序博客网 时间:2024/06/10 03:04

LeetCode小白菜笔记[10]:Implement strStr()

28. Implement strStr() [Easy]

题目:Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"Output: -1

简言之,就是把后一个子串(needle)从前一个字符串(haystack)中提取出来,返回其第一次出现的位置,若不存在则返回 -1 。

代码比较简单,不过特殊情况比较坑。。。按照题目的意思,如果 needle 是空的,则返回 0 ,即认为在第一个位置找到了。改了好几次才通过。代码如下:

class Solution(object):    def strStr(self, haystack, needle):        """        :type haystack: str        :type needle: str        :rtype: int        """        if not needle:            return 0        if len(haystack) < len(needle):            return -1        if len(haystack) == len(needle):            return int(haystack == needle) - 1        for idx in range(len(haystack) - len(needle) + 1):            if haystack[idx:idx+len(needle)] == needle:                return idx        return -1

结果如下:

这里写图片描述

discuss里面的代码更简洁:

class Solution(object):def strStr(self, haystack, needle):    """    :type haystack: str    :type needle: str    :rtype: int    """    for i in range(len(haystack) - len(needle)+1):        if haystack[i:i+len(needle)] == needle:            return i    return -1

有些特殊情况的处理可以纳入一般情况。如 len(needle)=0 的情况,haystack[ i : i ] = ”,因此返回0,符合题意,而且len(needle)比len(haystack)大的情况,由于haystack[ i : i + len(needle) ]如果后面的停止位置超出范围,则会一直取到haystack最末元素。因此永远不会相等,故最后 return - 1 。

总结:

通过设计算法将特殊情况纳入到普通情况来判断可以使得代码更简洁。

注意range和 [ i : j ] 的包含前项不包含后项的性质。

THE END

原创粉丝点击