博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode——Regular Expression Matching
阅读量:7081 次
发布时间:2019-06-28

本文共 1768 字,大约阅读时间需要 5 分钟。

hot3.png

'.' 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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true

原题如上

leetdcode给这道题打上的标记是有DP,虽然DP也能够做,但是我真的不认为DP是一个很直观的方法。好吧,我是普通青年,这题最难的地方在于backtracking,回溯,然而我卡在了这里。

对于匹配,一个很直观的方法就是贪心,尽可能的取匹配更多的字符。但是由于*这个字符可能匹配0个,1个或者多个,导致到底在匹配多少次上贪心算法并不能很好的控制。如果解决“*”这个字符的匹配难题呢?

我们还是以从头到尾的方式来匹配字符,对于‘*’的处理,我们是按照如下的:

  1. If the next character of p is NOT ‘*’, then it must match the current character of s. Continue pattern matching with the next character of both s and p.

  2. If the next character of p is ‘*’, then we do a brute force exhaustive matching of 0, 1, or more repeats of current character of p… Until we could not match any more characters.

如果下一个字符是'*',那么我们应该对匹配0次,1次,多次做一次暴力求解,考虑所有的情况。每一种情况,以一个递归的方式去解决。

既然是递归,那么就要好好地考虑base。我认为这个递归的base应该是待匹配串和匹配串都已经扫描完。

int isMatch(char* s, char* p){    assert(s && p); //s and p are null    if (*p == '\0')    {        return *s == '\0';    }    if (*(p+1) != '*')  //next character is not '*'    {        assert(*p != '*');        if ((*p == *s) || (*p == '.' && *s != '\0'))        {            return isMatch(s+1, p+1);        }else{            return 0;        }    }else{ //next character is '*', match 0, 1, 2,... times        while ((*p == *s) || (*p == '.' && *s != '\0'))        {            if (isMatch(s, p+2))            {                return 1;            }            s++;        }        return isMatch(s, p+2);    }}

转载于:https://my.oschina.net/u/1047616/blog/497169

你可能感兴趣的文章
请求(Request)的参数(Parameter)里包含特殊字符(#等)的正确处理方式
查看>>
PHP如何解决网站大流量与高并发的问题
查看>>
李洪强经典面试题43
查看>>
Android View体系(二)实现View滑动的六种方法
查看>>
Http请求中Content-Type和Accept讲解以及在Spring MVC中的应用
查看>>
NGINX反向代理
查看>>
MySQL集群---②Windows平台搭建MySQL CLUSTER集群
查看>>
完整部署CentOS7.2+OpenStack+kvm 云平台环境(6)--在线调整虚拟机的大小
查看>>
UEditor百度编辑器,工具栏自定义添加一个普通按钮
查看>>
HOLOLENS程序发布,这个界面调用的图片
查看>>
Atitit. Api 设计 原则 ---归一化
查看>>
JVM之数据类型
查看>>
【MongoDB】3.详细命令集合
查看>>
腾讯企业大学培训经验
查看>>
[LeetCode] Sort Characters By Frequency 根据字符出现频率排序
查看>>
python写的分析mysql binlog日志工具
查看>>
webapi - 使用依赖注入
查看>>
ubuntu 下非交互式执行远程shell命令
查看>>
centos7环境安装rabbitMQ
查看>>
时间换算方法
查看>>