[Leetcode] 28. Implement strStr()

来源:互联网 发布:比特币挖矿程序 mac 编辑:程序博客网 时间:2024/05/21 17:22

Problem:

Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Idea:
Use two points to go through these two string individually.

Solution:

class Solution(object):    def strStr(self, haystack, needle):        i=j=0        lenhaystack = len(haystack)        lenneedle = len(needle)        if lenneedle == 0:            return 0        while j!= lenhaystack:            if haystack[j] == needle[i]:                if i+1 == lenneedle:                    return j-i                else:                    i += 1                    j += 1            elif i != 0:                j = j-i+1                i = 0            else:                j += 1        return -1
0 0
原创粉丝点击