• 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

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    nio/mina(三) mina传对象
    Android系统中长按事件的实现机制解析
    android游戏寻路算法
    Xcode 常用快捷键及代码自动排版
    java 日期加天数得到新的日期
    cygwin 中文乱码问题
    Android 中自定义手势
    mina服务端与c++客户端通信1
    java NIO 和阻塞I/O的区别
    Android读写文件
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/11698230.html
Copyright © 2020-2023  润新知