有没有更好的pythonic方法来重写while循环?

时间:2019-10-22 04:45:04

标签: python

我编写此函数来执行strStr函数:

def strStr(haystack: str, needle: str) -> int:
    if not needle:
        return 0

    len_h = len(haystack)
    len_n = len(needle)

    if len_n > len_h:
        return -1

    index_h = 0
    index_n = 0
    matched_count = 0
    while index_h < len_h and index_n < len_n:
        v_h = haystack[index_h]
        v_n = needle[index_n]
        if v_h != v_n:
            index_h = index_h - matched_count + 1
            index_n = 0
            matched_count = 0
        else:
            index_h += 1
            index_n += 1
            matched_count += 1

        if index_n == len_n:
            return (index_h - len_n)

    return -1


print(strStr('hello', 'll'))
print(strStr('mississippi', 'issip'))

while循环是C或Java方式。我试图在Python中用于...。但是没有成功,因为我需要根据条件更新索引。 Python中的for循环似乎不起作用。还是有一种Python方法可以替换while循环吗?

1 个答案:

答案 0 :(得分:0)

Python有一个字符串方法.find(),该方法使用Boyer-Moore方法(https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm)实现。

这包含几个while循环。所以我会说这是一种合理的Python方式。