动态规划——正则表达式匹配
来源:互联网 发布:北京linux培训机构 编辑:程序博客网 时间:2024/06/06 04:55
题目链接:http://www.lintcode.com/zh-cn/problem/regular-expression-matching/
参考资料:http://www.cnblogs.com/wuchaodzxx/p/5846284.html 【思路正确,但是伪代码写错了:字符串中的第j个字符的位置应该是j-1】
///////////////////动态规划public boolean match(char[] str, char[] pattern) {boolean[][] dp = new boolean[str.length + 1][pattern.length + 1];dp[0][0] = true;for (int j = 1; j < dp[0].length; j ++) { //dp[0].length表示列数if(pattern[j - 1] == '*' && j>=2) dp[0][j] = dp[0][j - 2];}for (int i = 1; i < dp.length; i ++) { //dp.length表示行数for (int j = 1; j < dp[0].length; j ++) {//if(pattern[j - 1] == '.' || pattern[j - 1] == str[i - 1]) dp[i][j] = dp[i - 1][j - 1];//当模式的字符为*时:分两种情况else if(pattern[j - 1] == '*' && i>=2) {if(pattern[j - 2] != str[i - 1] && pattern[j - 2] != '.') dp[i][j] = dp[i][j - 2];else dp[i][j] = dp[i][j - 1] || dp[i][j - 2] || dp[i - 1][j];}}}return dp[str.length][pattern.length];}
上面的动态规划比较难理解,采用下面的方法:
public class RegularExpressionMatching {public boolean isMatch(String s, String p) { if(s==""||p=="") return false; char[] str=s.toCharArray(); char[] pattern=p.toCharArray(); int strIndex=0; int patternIndex=0; return matchCore(str, strIndex, pattern,patternIndex ); }public boolean matchCore(char[] str, int strIndex, char[] pattern, int patternIndex) {//有效性检验:str到尾,pattern到尾,匹配成功if (strIndex == str.length && patternIndex == pattern.length) {return true;}// pattern先到尾,匹配失败if (strIndex != str.length && patternIndex == pattern.length) {return false;}// 模式第2个是*,且字符串第1个跟模式第1个匹配,分3种匹配模式;如不匹配,模式后移2位if (patternIndex + 1 < pattern.length && pattern[patternIndex + 1] == '*') {if ((strIndex != str.length && pattern[patternIndex] == str[strIndex])|| (pattern[patternIndex] == '.' && strIndex != str.length)) {return matchCore(str, strIndex, pattern, patternIndex + 2)// 模式后移2,视为x*匹配0个字符|| matchCore(str, strIndex + 1, pattern,patternIndex + 2)// 视为模式匹配1个字符|| matchCore(str, strIndex + 1, pattern, patternIndex);// *匹配1个,再匹配str中的下一个} else {return matchCore(str, strIndex, pattern, patternIndex + 2);}}// 模式第2个不是*,且字符串第1个跟模式第1个匹配,则都后移1位,否则直接返回falseif ((strIndex != str.length && pattern[patternIndex] == str[strIndex])|| (pattern[patternIndex] == '.' && strIndex != str.length)) {return matchCore(str, strIndex + 1, pattern, patternIndex + 1);}return false;}}
阅读全文
0 0
- 动态规划——正则表达式匹配
- String、动态规划——正则表达式匹配
- 【动态规划】正则表达式匹配
- 第10题 正则表达式匹配(动态规划)
- 动态规划——通配符匹配算法
- 正则表达式——匹配固定长度
- 正则表达式5——重复匹配
- 正则表达式6——位置匹配
- 正则表达式——匹配数字
- 正则表达式——最小匹配问题
- 正则表达式——匹配(egrep)
- 正则表达式——密码规则匹配
- 《剑指offer》——正则表达式匹配
- 《剑指offer》——正则表达式匹配
- 剑指offer——正则表达式匹配
- 正则表达式——位置匹配
- 字符串匹配——正则表达式
- 字符串——正则表达式匹配
- C++标准转换运算符const_cast
- 分享一个内容管理系统网站
- hasChildNodes方法;ownerDocument;
- Event Service
- React.js 官网资料摘记:列表&keys
- 动态规划——正则表达式匹配
- 【mfc】mfc双击按钮时出现重载xxxx函数已经存在问题
- 构建缓存时选用NSCache而非NSDictionary
- 远程热部署项目到tomcat服务器中
- 栈回溯----X64
- 使用单用户模式重置Linux系统root密码
- shell初识-1
- JavaScript 语句
- Java程序员成长的几大成长法则