给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回  -1 。

当 needle 为空字符串时,返回0。

示例

输入:haystack = "hello", needle = "ll"

输出:2

解析

1)这个需求在python是index() / find(),需要注意的是 index() 没有匹配项时会报错

2)按常规解法来做,遍历 haystack,截取和 needle 等长的字符串进行比较,相同则返回索引位置即可

代码示例

def strStr(haystack, needle):
    l1 = len(haystack)
    l2 = len(needle)
    for i in range(l1-l2+1):
        if haystack[i:i+l2] == needle:
            return i
    return -1

print(strStr('abc','c'))

执行用时:28 ms, 在所有 Python3 提交中击败了 98.42% 的用户.

本文为 陈华 原创,欢迎转载,但请注明出处:http://www.ichenhua.cn/read/353