leetcode implement strStr

本文深入讲解了KMP算法的核心概念及其实现细节,包括Next数组的含义及其计算方法,并提供了优化后的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I wanna make a summary for KMP. 

Next[j] means that  max{ Next[j]| needle[j-Next[j]..j-1] == needle[0..Next[j]-1] }, i.e., at most k characters before needle[j] are matching the first k characters of needle(needle[0..k-1]), i.e., if (haystack[i] != needle[j])  at least haystack[i-j..i-1] == needle[0..j-1] and needle[0..next[j]-1] == needle[j-next[j]..j-1], so in the next turn, we should compare haystack[i] and needle[ next[j] ] to determine whether bring forward i and j. The array next is also calculated by this way. The following is the code. 

class Solution {
 public:
  char *strStr(char *haystack, char *needle) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    if (needle == NULL || haystack == NULL)
      return NULL;
    int i = 0, j = -1, needlelen = strlen(needle), haystacklen = strlen(haystack);
    if (needlelen > haystacklen)
      return NULL;
    if (needlelen == 0)
      return haystack;
    
    vector<int> next(needlelen+1, -1);
    while (needle[i]) {
      if (j == -1 || needle[i] == needle[j]) {
        ++i;
        ++j;
        next[i] = j;
      }
      else
        j = next[j];
    }
    i = 0;
    j = 0;
    while (haystack[i]) {
      if (j == -1 || haystack[i] == needle[j]) {
        ++i;
        ++j;
        if (needle[j]=='\0')
          return haystack+i-j;
      }
      else
        j = next[j];
    }
    return NULL;
  }
};

Meanwhile, there's another improvement for this code. For example, 


The following is obviously better. 



The code after improvement is :

class Solution {
 public:
  char *strStr(char *haystack, char *needle) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    if (needle == NULL || haystack == NULL)
      return NULL;
    int i = 0, j = -1, needlelen = strlen(needle), haystacklen = strlen(haystack);
    if (needlelen > haystacklen)
      return NULL;
    if (needlelen == 0)
      return haystack;
    
    vector<int> next(needlelen+1, -1);
    while (needle[i]) {
      if (j == -1 || needle[i] == needle[j]) {
        ++i;
        ++j;
        if (needle[i] != needle[j])
          next[i] = j;
        else
          next[i] = next[j];
      }
      else
        j = next[j];
    }
    i = 0;
    j = 0;
    while (haystack[i]) {
      if (j == -1 || haystack[i] == needle[j]) {
        ++i;
        ++j;
        if (needle[j]=='\0')
          return haystack+i-j;
      }
      else
        j = next[j];
    }
    return NULL;
  }
};







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值