44. Wildcard Matching

这里写图片描述

第一种方法:迭代回溯
两个指针,一个维持pattern的位置,一个维持str的位置,每一次循环str的idx或者pattern的idx至少有一个会往后移动一步。

当strIdx < srtLen的时候,因为存在这个pattern所以要进行尝试,加入匹配0个、1个、2个..试试看能不能匹配到最后,方法是记录上次遇到*的时候的PatternIdx和strIdx,如果后面没有匹配上,那么strIdx就从下一个开始匹配,patternIdx不变。
最后结束了以后,因为到这里的时候str一定已经结束了pattern可能有剩下的,所以还要排除掉‘ ’,最后看pattern的指针是否指到最后。

class Solution {
public:
    bool isMatch(string s, string p) 
    {
        int s1=0,
            p1=0,
            sLen=s.size(),
            pLen=p.size(),
            lastPatternIdx=-1,
            lastStrIdx=-1;
        while(s1<sLen)
        {
            if(p1<pLen && (s[s1]==p[p1] || p[p1]=='?'))
            {
                p1++;
                s1++;
            }
            else if(p1<pLen && p[p1]=='*')
            {
                lastPatternIdx=p1;
                lastStrIdx=s1;
                p1++;
            }
            else if(lastPatternIdx>-1)
            {
                p1=lastPatternIdx+1;
                s1=++lastStrIdx;
            }
            else
                return false;
        }
        while(p[p1]=='*')
            p1++;
        return p[p1]=='\0';
    }
};

第二种方法:动态规划

class Solution {
public:
    bool isMatch(string s, string p) 
    {
        int m=s.size();
        int n=p.size();
        vector<vector<bool> >match(m+1,vector<bool>(n+1,false));
        match[0][0]=true;
        int i,j;
        for(j=1;j<=n;j++)
        {
            if(p[j-1]=='*'&&match[0][j-1])
                match[0][j]=true;
        }
        for(i=1;i<=m;i++)
            for(j=1;j<=n;j++)
            {
                if(p[j-1]!='*')
                {
                    if(match[i-1][j-1]&&(p[j-1]=='?'||s[i-1]==p[j-1]))
                        match[i][j]=true;
                    //else
                    //  match[i][j]=false;
                }
                else//关键步骤
                {
                    if(match[i-1][j]||match[i][j-1])
                        match[i][j]=true;
                }
            }
        return match[m][n];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值