Implement strStr()

本文详细介绍了如何使用Boyer-Moore算法高效实现字符串搜索功能,通过预处理减少匹配次数,显著提升搜索性能。算法原理、代码实现及与KMP算法的对比分析,帮助开发者掌握一种快速、高效的字符串搜索技术。

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

Problem:

Implement strStr().

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

我实现了Boyer-Moore算法,效果非常好,12ms就跑下来了。BM算法的效率非常高,优于KMP算法。算法的详细介绍,我参考了博客
http://www.ruanyifeng.com/blog/2013/05/boyer-moore_string_search_algorithm.html​。



class Solution {
public:
     char *strStr(char *haystack, char *needle) {
    if(NULL==haystack||NULL==needle)
         return NULL;
    int plen = strlen(needle);
     int slen = strlen(haystack);
     if(0==plen)
         return haystack;
     else if(plen>slen)
         return NULL;
    int badChar[256];
    int np = 0;
    int i,j,k;

    for(i=0;i<256;i++)
         badChar[i] = plen;
    
     while(np<plen)
    {
         badChar[*(needle+np)] = plen-np-1;
         np++;
     }

    int* goodSuffix = new int[plen];

    int prefix_index = plen;
    for(i=plen-1;i>=0;i--)
     {
         goodSuffix[i] = prefix_index;
         if(*(needle+i)==*(needle+plen-1-i)&&prefix_index==i+1)
             prefix_index = i;
    }

    for(i=0;i<plen-1;i++)
    {
         j = plen-1, k = 0;
         while(k<i&&*(needle+j)==*(needle+i-k))
         {j--;k++;}
         if(*(needle+plen-1)==*(needle+i))
             goodSuffix[j] = plen-1-i;
    }
     goodSuffix[plen-1] = 0;

    int sp = 0;
     while(sp<slen)
    {
         i = plen-1;
          while(i>=0&&*(haystack+sp+i)==*(needle+i))
             i--;
          if(i<0)
            return haystack+sp;
         int bj = badChar[*(haystack+sp+i)] - plen + i + 1;
         sp += (bj>goodSuffix[i]?bj:goodSuffix[i]);
     }

    delete goodSuffix;
     return NULL;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值