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

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

题目:( DP ,BackTracking, String)

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

题解:

本文及代码引用自:http://harrifeng.github.io/algo/leetcode/regular-expression-matching.html
  • 首先要理解题意:
    • "a"对应"a", 这种匹配不解释了
    • 任意字母对应".", 这也是正则常见
    • 0到多个相同字符x,对应"x*", 比起普通正则,这个地方多出来一个前缀x. x代表的是 相同的字符中取一个,比如"aaaab"对应是"a*b"
    • "*"还有一个易于疏忽的地方就是它的"贪婪性"要有一个限度.比如"aaa"对应"a*a", 代码逻辑不能一路贪婪到底
  • 正则表达式如果期望着一个字符一个字符的匹配,是非常不现实的.而"匹配"这个问题,非 常容易转换成"匹配了一部分",整个匹配不匹配,要看"剩下的匹配"情况.这就很好的把 一个大的问题转换成了规模较小的问题:递归
  • 确定了递归以后,使用java来实现这个问题,会遇到很多和c不一样的地方,因为java对字符 的控制不像c语言指针那么灵活charAt一定要确定某个位置存在才可以使用.
  • 如果pattern是"x*"类型的话,那么pattern每次要两个两个的减少.否则,就是一个一个 的减少. 无论怎样减少,都要保证pattern有那么多个.比如s.substring(n), 其中n 最大也就是s.length()
public class Solution {    public boolean isMatch(String s, String p) {        if(p.length()==0)          return s.length()==0;                  if(p.length()==1)            return (s.length()==1)&&(p.charAt(0)==s.charAt(0)||p.charAt(0)=='.');        if(p.charAt(1)!='*')        {            if(s.length()==0)               return false;            else                 return isMatch(s.substring(1),p.substring(1))&&(s.charAt(0)==p.charAt(0)||p.charAt(0)=='.');        }        else        {            while(s.length()>0&&(s.charAt(0)==p.charAt(0)||p.charAt(0)=='.'))            {                if(isMatch(s,p.substring(2)))                   return true;                                   s=s.substring(1);            }                        return isMatch(s,p.substring(2));        }    }}

 

转载于:https://www.cnblogs.com/fengmangZoo/p/4183804.html

你可能感兴趣的文章
phpcms v9 配置sphinx全文索引教程
查看>>
使用C#和Java发送邮件(转载)
查看>>
转载:32位Win7使用4G内存
查看>>
Hadoop中eclipse 插件的编译 笔记四
查看>>
MariaDB备份之XtraBackup
查看>>
Activity间用Intent和Bundle传递参数
查看>>
记忆化搜索(DFS+DP) URAL 1501 Sense of Beauty
查看>>
HDU4624 Endless Spin(概率&&dp)
查看>>
js-新闻无缝滚动
查看>>
Python在自动化运维时最常用的50个方法(转)
查看>>
Java 学习之路 之 泛型方法
查看>>
Test
查看>>
C# 整理
查看>>
jQuery的效果函数
查看>>
AngularJS中使用$resource
查看>>
[poj3261]Milk Patterns(后缀数组)
查看>>
[luogu3369]普通平衡树(fhq-treap模板)
查看>>
题解 P2799 【国王的魔镜】
查看>>
写写代码,注意注意细节
查看>>
css Backgroud-clip (文字颜色渐变)
查看>>