leetcode 10 -- Regular Expression Matching

Regular Expression 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
isMatch(“aab”, “c*a*b”) → true


题意:
实现一个类似正则匹配,可以实现匹配.*.是匹配任意字符,*是匹配左边第一个字符0个或者多个。不熟悉正则的可以看看我的python正则表达式那篇文章^_^


思路:
我们肯定是按照字符一个一个匹配的,关键点不在.,如果是.,直接忽略继续跳转下一个即可,需要注意的是*。首先*是绝不会为第1个字符的(根据正则表达式规则,*是匹配最左边第一个字符,重复0次或者多次),我们只能从第二个字符开始确定号,接着我们就分成两种情况,1.有*,2.没有*,有*号时我们是不确定原串匹配字符的个数的(比如原串aaaab,和匹配串a*b,那么原串的aaaa对应的就是匹配串的a*),那么我们需要循环来判断是否匹配串*前面的字符和原串相等。此时匹配串不移动下标,原串不断的移动(因为原串是重复才能匹配 匹配串 的*的,比如上面的aaaa),直到满足条件后,我们下标跨过匹配串的*号,接着继续匹配,如果没有*号,就老老实实一个一个匹配。


代码:

int isMatch(char* s, char* p)
{
    //判断为空的情况   
    if(p[0] == '\0'){
        return s[0] == '\0';
    }
    //处理'*'匹配,必须假设当前串的第二个字符为'*',第一个不可能为'*',因为'*'是和左边第一个作用的
    if(p[1] == '*'){
        //判断原串前面的字符是否是和'*'前面的重复匹配,此时只移动原串,不移动匹配串
        while(s[0] != '\0' && (p[0] == '.' || s[0] == p[0])){
            if(isMatch(s, p+2))
                return 1;
            s++;    
        }
        return isMatch(s, p+2);
    }else{
        //处理非'*'号情况
        if(s[0] != '\0' && (p[0] == '.' || p[0] == s[0])){
            //原串和匹配串同时前进一个字符
            return isMatch(s+1, p+1);
        }
        return 0;
    }
}

#!/usr/bin/env python
#coding:UTF-8

def isMatch(s, p):
    if len(p) == 0:
        return len(s) == 0
    if len(p) == 1:
        return len(s) == 1 and p[0] == s[0]
    if p[1] == '*':
        while len(s) != 0 and (p[0] == '.' or p[0] == s[0]):
            if isMatch(s, p[2:]):
                return True
            s = s[1:]
        return isMatch(s, p[2:])
    else:
        if len(s) != 0 and (p[0] == '.' or p[0] == s[0]):
            return isMatch(s[1:], p[1:])
        return False

if __name__ == '__main__':
    print isMatch('aa', 'a')
    print isMatch('aa', 'aa')
    print isMatch('aaa', 'a')
    print isMatch('aa', '.*')
    print isMatch('ab', '.*')
    print isMatch('aab', 'c*a*b')
    print isMatch('aaaab', '.*ab')
    print isMatch('aaaaaaaaccc', 'a*ccc')

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夏天的技术博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值