【LeetCode 28】Implement strStr() (Python)

来源:互联网 发布:做微信动图软件叫什么 编辑:程序博客网 时间:2024/06/16 11:30

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题目分析:判断needle给出的字符串是否是haystack给出的字符串的子串。如果是返回needle第一个字符在haystack出现的位置。
示例:
Input: haystack = “hello”, needle = “ll”
Output: 2

Input: haystack = “aaaaa”, needle = “bba”
Output: -1

方法一:

  1. 思路:检测字符串是否包含某字符串时,在python中有两个现成的方法—–index()和find()。
  2. 优点:代码短,简单。直接就可以返回对应位置。 时间复杂度O(1)。
    缺点:有局限性,只适用于这道题。
  3. 代码:
class Solution:    def strStr(self, haystack, needle):        """        :type haystack: str        :type n eedle: str        :rtype: int        """        if needle in haystack:            return haystack.find(needle)        else:            return -1
class Solution:    def strStr(self, haystack, needle):        """        :type haystack: str        :type n eedle: str        :rtype: int        """        if needle in haystack:            return haystack.index(needle)        else:            return -1

方法二:

  1. 思路:循环haystack(不全循环,只到needle首字母出现的位置即可),当遇到与needle首字母相同时,检查haystack从该位置开始的与needle长度相同的部分的内容是否相同。如果是返回首字母出现的位置,否则返回-1。
  2. 优点:换一部分代码就可用于其他情况,适用范围广。也好懂。
    缺点:代码较长。时间复杂度应该是O(n)吧(这个因为包含了好几个if还有while所以不太会算,好像还要结合概率论。会算的可以在评论里教教我,不胜感激
  3. 代码:
class Solution:    def strStr(self, haystack, needle):        """        :type haystack: str        :type n eedle: str        :rtype: int        """        if not needle:            return 0        for i in range(len(haystack)-len(needle)+1):            if haystack[i]==needle[0]:                j=1 #用来记数needle已经检查了几个字母                while j<len(needle) and haystack[i+j]==needle[j]:                    j+=1                if j==len(needle):                    return i        return -1