leetcode——28. 实现 strStr()

简单题

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if needle=='':
            return 0
        if len(needle)>len(haystack):
            return -1
        if len(needle)==len(haystack):
            if needle==haystack:
                return 0
            else:
                return -1
        n=len(needle)
        i=0
        while i<len(haystack)-n+1:
            if haystack[i:i+n]==needle:
                return i
            else:
                i+=1
        return -1
执行用时 :40 ms, 在所有 python3 提交中击败了93.62%的用户
内存消耗 :13.9 MB, 在所有 python3 提交中击败了5.88%的用户
 
                                                                            ——2019.10.18
 

复习。
还好吧,就直接用暴力法解决的了,KMP算法到现在为止还是不会的,就慢慢学习。
public int strStr(String haystack, String needle) {  //用暴力法求解
        if(needle.length() == 0){
            return 0;
        }
        if(haystack.length() == 0){
            return -1;
        }
        int i = 0,j = 0,k = 0;
        while(k<haystack.length() - needle.length()+1){
            i = k;
            while(i<haystack.length() && j<needle.length() && haystack.charAt(i) == needle.charAt(j)){
                i++;
                j++;
            }
            k++;
            if(j == needle.length()){
                return k-1;
            }
            j = 0;
        }
        return -1;
    }

 

 

——2020.7.6

 

posted @ 2019-10-18 14:45  欣姐姐  阅读(140)  评论(0编辑  收藏  举报