zoukankan      html  css  js  c++  java
  • [leecode]Implement strStr()

    Implement strStr()

    Implement strStr().

    Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

    实现String.class中的contains()接口。

    KMP算法

    不了解该算法的,请移步KMP算法小结。这个也属于必须要掌握的算法。

    【未通过case】needle == “”

    代码如下:

    public class Solution {
        public String strStr(String haystack, String needle) {
            if(haystack == null || needle == null || haystack.length() < needle.length() || (haystack.length() == needle.length() && !haystack.equals(needle)) ) return null;//needle为空串要特别注意
            if(needle.equals("") || haystack.equals(needle)) return haystack;
            int i = 0, j = 0;
            int[] next = new int[needle.length()];
            setNext(needle,next);
            while(i < haystack.length()){
                if(j == -1 || haystack.charAt(i) == needle.charAt(j)){
                    i++;
                    j++;
                }else{
                    j = next[j];
                }
                if(j == needle.length()) return haystack.substring(i - needle.length());
            }
            return null;
        }
        private void setNext(String needle,int[] next){
            char[] p = needle.toCharArray();
            int length = p.length;
            int k = -1, j = 0;
            next[0] = -1;
            while(j < length - 1){
                if(k == -1 || p[k] == p[j]){
                    next[++j] = ++k;
                }else{
                    k = next[k];
                }
            }
        }
        
    }

    这道题我整理了整整一天,第一次手动的实现了KMP,并作出KMP算法小结。后天还要再复习一下。

  • 相关阅读:
    开启进程
    操作系统
    多线程(进程)目录
    网络编程-基于UDP协议套接字
    网络编程-文件传输
    EXt js 学习笔记总结
    Sencha Toucha 2.1 文件上传
    Sencha Touch 2.1学习图表Chart概述
    Sencha Touch 2.1 Chart属性中文解释
    Ext.Ajax.request方法 参数
  • 原文地址:https://www.cnblogs.com/huntfor/p/3971953.html
Copyright © 2011-2022 走看看