2019-05-18LeetCode28. 实现strStr()

2019-05-18  本文已影响0人  mztkenan

暴力法自己写就超时了

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if(needle==''):return 0
        for i in range(len(haystack)):
            same=True
            for j in range(len(needle)):
                if(i+j>=len(haystack) or needle[j]!=haystack[i+j]):same=False;break
            if same==True:return i
        return -1
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if(needle==''):return 0
        for i in range(len(haystack)-len(needle)+1):
            if(needle==haystack[i:i+len(needle)]):return i
        return -1

巧妙,逻辑顺序换一下就不用处理特殊情况,而且还不会超时??

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        for i in range(len(haystack)+1):
            for j in range(len(needle)+1):
                if(j==len(needle)):return i
                if(i+j==len(haystack)):return -1
                if(haystack[i+j]!=needle[j]):break
上一篇 下一篇

猜你喜欢

热点阅读