LeetCode刷题-28——Implement strStr()

链接:

https://leetcode.com/problems/implement-strstr/description/

题目:

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

Example:

Example 1:

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

Example 2:

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

Notes:

解析:

  • 返回haystack中第一次出现needle的索引,如果没有,返回-1
  • strip函数:strip()方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
  • find函数:find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。

解答:

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

猜你喜欢

转载自blog.csdn.net/u014135752/article/details/80672123