leetcode Regular Experssion Matching

 10.Regular Experssion Matching

题目描述:

Implement regular expression matching with support for '.' and '*'.
'.' 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

递归思路:p代表匹配模式,s代表待匹配的字符串,首先考虑p的3种特殊情况,len(p)=0,len(p)=1和p=".*".

len(p) =0时,匹配空字符串;

len(p)=1时,如果 p="."匹配任意单个字符,否则s要和p相等才匹配

p=".*"时,直接返回True,匹配任意字符串

然后是一般情况就需要用到递归了,对p分两种情况分别进行递归,p[1]='*'和p[1] != '*'.

p[1]!='*'时,p[0]就不可省略,s要能匹配成功,s[0]必须和p[0]匹配,当s[0]和p[0]匹配成功后,就可以递归的匹配s和p剩下的字符串了.

p[1]='*'时,p[0]就可以出现0次到无数次,比如a*可以匹配空字符串,a,aa,aaa, . . . . .等,这个时候就需要循环匹配p所有的可能字符串.

完整代码:

class Solution(object):
    def isMatch(self, s, p):
        if p == '.*':
            return True
        if len(p) == 0:
            return len(s) == 0
        if len(p) == 1:
            return True if p[0]== '.'and len(s) == 1 else (len(s)==1 and s[0]==p[0])
        if p[1] != '*':
            return False if len(s) == 0 or (p[0] != '.' and  p[0]!=s[0]) else  self.isMatch(s[1:],p[1:])
        else:
            index ,length = -1,len(s)

    #循环每次都舍弃s中最近和p[0]匹配成功的字符的前面的子串(包含该字符),然后匹配剩下的s和p[2:]匹配,直到找到能和p[2:]匹配成功的s,循环结束还没找到就说明s和p匹配失败.

            while index<length and (index < 0 or p[0]=='.' or  p[0] == s[index]):
                if self.isMatch(s[index+1:],p[2:]):
                    return True
                index += 1
        return False



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值