【字符串匹配】KMP(implement strStr()), 正则匹配(Wildcard Matching),2-dim 动规(regular expression)

本文详细介绍了字符串匹配算法,包括KMP算法实现的strStr()函数,以及正则匹配问题的解决策略。正则匹配涉及到回溯和贪心法,重点讨论了'*'号的处理规则。同时,文章还探讨了支持'.'和'*'的2D动态规划解决方案,以实现更复杂的模式匹配需求。
摘要由CSDN通过智能技术生成

1 KMP

 

Implement strStr()

  Total Accepted: 15450  Total Submissions: 71217 My Submissions

Implement strStr().

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

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        int n=strlen(needle);
        if(n==0)  return haystack;
         //kmp
        vector<int> nxt(n+1);///@error: nxt should be sized n+1, not n. to contain the nxt[n]
        nxt[0]=-1;nxt[1]=0;
        for(int i=0;i<n;i++){
            int j=nxt[i];
            while(j>=0&&needle[i]!=needle[j]) j=nxt[j]; //i matched j
            nxt[i+1]=j+1;/@@@@@@@error: nxt[i+1]=j+1; mistake as needle[i+1]=j+1;  an Array_Variable_Fault !!!!
        }
        int j=0;
        for(int i=0;haystack[i]!=0;i++,j++){
            while(j>=0&&haystack[i]!=needle[j]) j=nxt[j];//i matched j
            if(j==n-1) return haystack+i-j; //matche needle
        }
        return NULL;
    }
};



 正则匹配不同于一般匹配。回溯取决于*号出现的位置。

 采用贪心法:p中'*'尽量匹配s中最少的字符,从上

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值