Leetcode(10)Regular Expression Matching

题目:字符串匹配。‘.’可以匹配任意字符,‘*’可以匹配任意多个相同的字符。

‘.’ Matches any single character.
‘*’ Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch(“aa”,”a”) → false
isMatch(“aa”,”aa”) → true
isMatch(“aaa”,”aa”) → false
isMatch(“aa”, “a*”) → true
isMatch(“aa”, “.*”) → true
isMatch(“ab”, “.*”) → true
isMatch(“aab”, “c*a*b”) → true


解法:

最简单的想法就是用递归:

1、递归出口:s字符串没结束,p结束了。不匹配。

                          s字符串结束,p结束。匹配。

                          s字符串结束,p没结束但是后面都是字母加星号的结构。匹配。

 2、递归过程:                        

                         如果p[i+1]为‘*’,p可以匹配s任意多个等于p[i]的字符。对一个,两个,...的情况都判断一下,如果有一种情况可以,就返回true,否则返回false。

                         如果p[i+1]不为“*”,则要p[i]=s[i],并且后面的字符串也要匹配,才返回true。否则返回false。

代码:

class Solution {
public:
    bool isMatch(string s, string p) {
        return isMatch_(0,0,s,p);
    }
    
    bool isMatch_(int i,int j,string& s,string& p)
    {
        int len1=s.length(),len2=p.length();
        if(i!=len1&&j==len2) return false;
        if(i==len1&&j==len2) return true;
        if(i==len1&&j!=len2)
        {
            while(j+1<len2&&p[j+1]=='*') j+=2;
            if(j==len2) return true;
            else return false;
        }
        
        if(j+1<len2&&p[j+1]=='*')
        {
            if(isMatch_(i,j+2,s,p)) return true;
            while(i<len1&&(s[i]==p[j]||p[j]=='.'))
            {
                i++;
                if(isMatch_(i,j+2,s,p)) return true;
            }
            return false;
        }
        else if(s[i]==p[j]||p[j]=='.')
        {
            return isMatch_(i+1,j+1,s,p);
        }
        else return false;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值