python实现strStr()函数

思路:

1、如果待查找子串为空,返回0(与c/c++的库函数保持一致);

2、如果大字符串的长度小于待查找子串的长度,返回-1;

3、计算需要编译的字符串下标位置:l = l1 - l2 + 1; 

4、从下标0到下标l遍历长字符串,截取与待查找子串长度相同的子字符串,判断内容是否与待查找子串相同,相同返回下标i;

5、默认找不到匹配的子串,返回-1。

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not needle:
            return 0
        l1 = len(haystack)
        l2 = len(needle)

        if l1 < l2:
            return -1

        l = l1 - l2 + 1
        for i in range(l):
            if haystack[i:i+l2] == needle:
                return i
        return -1

猜你喜欢

转载自blog.csdn.net/u011376563/article/details/82888137