首先来看下这个题目的问题:简言之就是要求一个字符串中,某一个子串它的下标,如果有,则返回这个子串首次出现的下标,如果没有,就返回-1,下面是原题:
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
接下来说说我的想法,首先我要判断这两个字符串的长度,如果子串比母串的长度还要长,那就返回-1,如果子串和母串都是空的字符串,那就返回0,这是两个特殊情况,接下来其他的情况,我用子串的长度去做一个索引,用来检索母串中的子字符串,比如子串长度是2,那么我就用2这个长度去依次遍历母串,每两个元素一起和子串比较,如果相等,就返回这个下标i的值。依次遍历至字符串结束,代码如下:
#-*-Coding:UTF-8-*- class Solution: def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ num = len(needle) if len(haystack) < num: return -1 elif haystack == "" and needle == "": return 0 else: for i in range(len(haystack)):#0 1 2 3 4 if(haystack[i:num+i]==needle):#[0:2] return i return -1 if __name__ == '__main__': S = Solution() h = input("") n = input("") print(h) print(n) print(S.strStr(h,n))
程序运行结果如下图:
我写了两个输出语句用来检测输入是否正确
到这里,这个问题就解决的差不多了,另外我想,如果还有类似的问题,不再是求初始出现的下标,我该怎么做,我觉得应该不难,多次输出就是了,这个算法的时间复杂度是O(n) n是母串的长度
2018.12.12 1:12am