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

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

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 注意*表示前一个字符的个数,可以为0. 动态规划的一题:扫描到s的第i个字符和p的第j个字符时状态的确定:当p当前扫描到的第j个字符字符不为‘*’时,判断p当前的字符和s当前的字符是否匹配,如果匹配则置true,否则置false;               当p当前扫描到的第j个字符为‘*’时,如果i-1之前的字符和j之前的字符能匹配且s的第i个字与p的j-1个匹配,则置true                                            否则如果s的前i个字符和p的前j-1个字符或p的前j-2个字符匹配,则置true;
1 public class Solution { 2     public boolean isMatch(String s, String p) { 3         int m=s.length(); 4         int n=p.length(); 5         boolean dp[][]=new boolean[m+1][n+1]; 6         dp[0][0]=true; 7         for(int i=1;i<=m;i++){ 8             dp[i][0]=false; 9         }10         for(int j=1;j<=n;j++){11             if(p.charAt(j-1)!='*')12              dp[0][j]=false;13              else{14                   dp[0][j]=dp[0][j-2];15              }16       }17       18       for(int i=1;i<=m;i++)19       for(int j=1;j<=n;j++){20           if(p.charAt(j-1)!='*'){21               if(dp[i-1][j-1]&&(s.charAt(i-1)==p.charAt(j-1)||p.charAt(j-1)=='.')) 22               dp[i][j]=true;23               else dp[i][j]=false;24               25           }else{26               if(dp[i-1][j] && (s.charAt(i-1) == p.charAt(j-2)||p.charAt(j-2)=='.'))dp[i][j]=true;27               else   if (dp[i][j-1]||dp[i][j-2]) dp[i][j]=true;28               else dp[i][j]=false;29           }30       }31       32       return dp[m][n];33            34     }35 }
View Code

 

 

转载于:https://www.cnblogs.com/gonewithgt/p/4558957.html

你可能感兴趣的文章
使用shutdown命令实现局域网内远程关机、重启整蛊他人
查看>>
Struts 笔记 内部资料 请勿转载 谢谢合作
查看>>
去面试吧!CSS
查看>>
hdu 1045
查看>>
使用时间戳和sequence生成主键的function
查看>>
用字体开透明窟窿
查看>>
淡入淡出的效果
查看>>
Python加密与解密
查看>>
C++在Ubuntu上编译mysql问题
查看>>
Java学习--Cookie 和session
查看>>
rem布局在webview中页面错乱
查看>>
第12章:MongoDB-CRUD操作--文档--查询--游标详解
查看>>
C语言中环境变量操作
查看>>
[codeforces 519E]E. A and B and Lecture Rooms(树上倍增)
查看>>
SQL语句中的output
查看>>
jquery之过滤filter,not
查看>>
Ci 自己的分页类【原创】
查看>>
JavaScript编写自己的比特币交易代码
查看>>
THE START OF ASE
查看>>
使用mongodump及mongorestore备份及恢复数据
查看>>