Regular Expression Matching,regex,正则表达式匹配,利用动态规划
2016-05-24 19:49
543 查看
问题描述:Implement regular expression matching with support for
算法分析:.*可以匹配任意字符串,例如ab匹配.*,不是说让.匹配完a然后再去匹配*,而是*匹配的是.,也就是说(.*)==(..........),所以.*匹配所有字符串。
利用动态规划,对于匹配字符串p,讨论三种情况,p长度为0,p长度为1,p的长度大于1(p的第二字符串为*,p的第二个字符串不为*)
'.'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
算法分析:.*可以匹配任意字符串,例如ab匹配.*,不是说让.匹配完a然后再去匹配*,而是*匹配的是.,也就是说(.*)==(..........),所以.*匹配所有字符串。
利用动态规划,对于匹配字符串p,讨论三种情况,p长度为0,p长度为1,p的长度大于1(p的第二字符串为*,p的第二个字符串不为*)
//动态规划 public class Regex2 { public boolean isMatch(String s, String p) { // p长度为0,边界条件。 if (p.length() == 0) { return s.length() == 0; } // p长度为1,边界条件。 if (p.length() == 1) { // s长度为0 if (s.length() < 1) { return false; } //首元素匹配有两种情况 // 如果p为.则s第一个元素和p一定匹配,如果p的第一个元素和s的第一元素相同,也一定匹配。 else if ((p.charAt(0) != s.charAt(0)) && (p.charAt(0) != '.')) { return false; } // 否则除了第一个匹配的元素外,比较其他的元素,动态规划的思想。 else { return isMatch(s.substring(1), p.substring(1)); } } // p的第二个元素不是*,*代表0个或多个前面的元素 if (p.charAt(1) != '*') { if (s.length() < 1) { return false; } else if ((p.charAt(0) != s.charAt(0)) && (p.charAt(0) != '.')) { return false; } else { return isMatch(s.substring(1), p.substring(1)); } } else //p的第二个元素是* { //*代表0个前面的元素 if (isMatch(s, p.substring(2))) { return true; } //*代表一个或多个前面的元素 //遍历s,如果s的i元素等于p的第一个元素,或者p的第一个元素为.,匹配s的i+1和p的第三个元素后的字符串 for(int i = 0; i<s.length() && (s.charAt(i) == p.charAt(0) || (p.charAt(0) == '.')); i ++ ) { if(isMatch(s.substring(i + 1), p.substring(2))) { return true; } } return false; } } public static void main(String[] args) { Regex2 reg2 = new Regex2(); System.out.println(reg2.isMatch("aaba", ".*")); } }
相关文章推荐
- window下使用vnc远程登录阿里云ECS/ubuntu图形界面
- 显示intent的使用讲解
- 透过 Linux 内核看无锁编程
- jdk在myeclipse中的配置
- Android之broadcast
- 弱也有弱的ACM经历
- 顺序表——链接表示
- 软件工程—Chapter2 计划
- 关于mt=8
- java I/O 学习笔记
- How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0
- 【OpenCV_03】图像载入,显示和输出 Read & Display Image
- 一些常见的Android运行失败原因
- bzoj1492 [NOI2007]货币兑换Cash
- Session
- 配置linux虚拟机本地yum源
- python爬虫模块安装
- 进程切换
- 遗传算法
- SQL SERVER T-SQL Programming