zoukankan      html  css  js  c++  java
  • LeetCode-Implement strStr()-KMP

    Implement strStr().

    Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

    Update (2014-11-02):
    The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button to reset your code definition.

    Solution:

     1 public class Solution {
     2     public int strStr(String haystack, String needle) {
     3         if (needle.isEmpty()) return 0;
     4         if (haystack.isEmpty()) return -1;
     5 
     6         int[] pm = getPartialMatchTable(needle);
     7         int p1 = 0, p2 = 0;
     8         while (p1<haystack.length() && p2<needle.length()){
     9             if (haystack.charAt(p1)==needle.charAt(p2)){
    10                 p1++;
    11                 p2++;
    12             } else {
    13                 if (p2==0) p1++;
    14                 else p2 = pm[p2-1]+1;
    15             }
    16         }
    17         if (p2<needle.length()) return -1;
    18         else return p1-p2;
    19         
    20     }
    21 
    22     public int[] getPartialMatchTable(String needle){
    23         int[] pm = new int[needle.length()];
    24         pm[0] = -1;
    25         for (int i=1;i<needle.length();i++){
    26             int j = pm[i-1];
    27             while (j>=0 && needle.charAt(i)!=needle.charAt(j+1))  j = pm[j];
    28             if (needle.charAt(i)==needle.charAt(j+1)) pm[i] = j+1;
    29             else pm[i] = -1;
    30         }
    31         return pm;
    32     }
    33 }
  • 相关阅读:
    百度API车牌识别——Restful方式
    cxgrid 满足条件颜色显示
    cxgrid 增加右键菜单
    折线图堆积图
    echarts 堆积图
    echarts 柱型图和折线图组合
    图表自动轮播
    Delphi D10.3 FMX android 调用自带浏览器打开网页
    echarts-JSON请求数据
    堆叠条形图
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4200270.html
Copyright © 2011-2022 走看看