zoukankan      html  css  js  c++  java
  • 面试题30:KMP 字符串查找

    参考:http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html
    自己写的很简单的KMP字符串匹配
     1 int KMP(string s,string p){
     2     int pLen = p.length();
     3     int* next = new int[pLen];
     4     next[0] = -1;
     5 
     6     int k = -1;
     7     int j = 0;
     8     while(j < pLen - 1){
     9         if(k == -1 || p[k] == p[j]){
    10             k++;
    11             j++;
    12             next[j] = k;
    13         }else{
    14             k = next[k];
    15         }
    16     }
    17 
    18     //print next array;
    19     for(int k=0;k<pLen;k++){
    20         std::cout << next[k]<< ",";
    21     }
    22     std::cout << std::endl;
    23 
    24     j = 0;
    25     size_t i = 0;
    26     size_t sLen = s.length();
    27     while(i<sLen && j < pLen){
    28         if(j == -1 || s[i] == p[j]){
    29             i++;
    30             j++;
    31         }else{
    32             j = next[j];
    33         }
    34     }
    35 
    36     delete next;
    37     if(j == pLen){
    38         return i - j;
    39     }else{
    40         return -1;
    41     }
    42 }

    Implement strStr().

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

     1 class Solution {
     2 public:
     3     char *strStr(char *haystack, char *needle) {
     4         if(haystack == nullptr || needle == nullptr) return nullptr;
     5 
     6         int i = 0,j =0;
     7         int start = 0;
     8         while(haystack[i] != '' && needle[j] != ''){
     9             if(haystack[i] == needle[j]){
    10                 i++;
    11                 j++;
    12             }else{
    13                 start++;
    14                 i = start;
    15                 j = 0;
    16             }
    17         }
    18         if(needle[j] == '') return haystack+start;
    19         else return nullptr;
    20     }
    21 };
  • 相关阅读:
    2013-2014 NBA 东西部决赛 + 总决赛合集
    小萌库
    小萌库一周电影大合集
    小萌库
    小萌库- 新海诚那些唯美感人的动漫
    小萌库 一周漫画精彩回顾
    小萌库
    Week10-数据库
    Week9-RabbitMQ、Redis、Mysql
    Week8-python(线程、进程、协程)
  • 原文地址:https://www.cnblogs.com/wxquare/p/4507208.html
Copyright © 2011-2022 走看看