【LeetCode】28. Implement strStr() 解题报告(Python)

题目分析:
这一题是较简单,就是匹配字符串返回位置可以逐位加上匹配串长度进行比较,相同了直接返回位置。

代码说明:
1、if not needle: return 0,匹配串为空返回0。
2、逐位加上匹配串长度进行比较,相同了直接返回位置。

            if i + l <= len(haystack):
                if haystack[i: i+l] == needle:
                    return i

3、else: break return -1没匹配到返回-1。

测试代码:

class Solution:
    def strStr(self, haystack, needle):
        l = len(needle)
        if not needle:  return 0
        for i in range(len(haystack)):
            if i + l <= len(haystack):
                if haystack[i: i+l] == needle:
                    return i
            else:
                break
        return -1

print(Solution().strStr('hello', 'll')) #提交时请删除该行

猜你喜欢

转载自blog.csdn.net/L141210113/article/details/88291546