【Leetcode】028-Implement strStr()

Question

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:

<pre>Input: haystack = "aaaaa", needle = "bba"
Output: -1
</pre>

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if len(needle)==0 :
            return 0
        elif needle in haystack:
            # return haystack.find(needle)
            return haystack.index(needle)
        else:
            return -1
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,140评论 0 10
  • 像我这么不懂得变通,不想改变,只想逃避的人还有吗?
    迷路在人生的路上阅读 695评论 0 0
  • 常青花园白领天地女子乐团开班啦……我们的乐团成员全是爱学习的零基础的宝妈们,而我们的老师却是有着几十年教学经...
    mr漠然阅读 1,527评论 0 0
  • “看热闹的朋友,别藏着掖着了,赶快出来吧。”云淼一掸拂尘,淡然道。 “道长耳朵好生灵敏,小生敬佩不已,敢问道长高姓...
    长楼阅读 2,682评论 0 0