美文网首页
2019-05-18LeetCode28. 实现strStr()

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

作者: mztkenan | 来源:发表于2019-05-18 16:54 被阅读0次

暴力法自己写就超时了

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

相关文章

网友评论

      本文标题:2019-05-18LeetCode28. 实现strStr()

      本文链接:https://www.haomeiwen.com/subject/ikbtzqtx.html