leetcode-10. Regular Expression Matching
来源:互联网 发布:java格式化日期24小时 编辑:程序博客网 时间:2024/06/10 23:16
leetcode-10. Regular Expression Matching
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”) → 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
我觉得这题是一个非常经典的题目。第二次还是没做出来。关键是这题为什么要用动态规划做?而不用其他方法做。或者说什么类型的题目最适合用动态规划做。
这题比较困难的问题是对于A*、.*、这类的问题有可能匹配0个1个或者多个。也就是说对于当前的问题是否可以匹配会有多个入口。。这类的问题是最容易用DP做出来的。
基本的思路这里有很好的解释。典型的DP解法
public class Solution { public boolean isMatch(String s, String p) { if( s == null || p == null) return false; boolean[][] dp = new boolean[s.length()+1][p.length()+1]; dp[0][0] = true; for(int i = 1 ; i < p.length() ; i++){ if (p.charAt(i) == '*' && dp[0][i-1]) dp[0][i+1] = true; } for(int i = 0 ; i < s.length() ; i++) for(int j = 0 ; j < p.length() ; j++){ if(s.charAt(i)==p.charAt(j) || p.charAt(j)=='.') dp[i+1][j+1] = dp[i][j]; else if(p.charAt(j)=='*'){ if(p.charAt(j-1)!='.' && p.charAt(j-1)!=s.charAt(i)){ dp[i+1][j+1] = dp[i+1][j-1]; }else{ dp[i+1][j+1] = (dp[i+1][j] || dp[i][j+1] || dp[i+1][j-1]); } } } return dp[s.length()][p.length()]; }}
- [LeetCode]10.Regular Expression Matching
- LeetCode --- 10. Regular Expression Matching
- [Leetcode] 10. Regular Expression Matching
- [LeetCode]10.Regular Expression Matching
- [leetcode] 10.Regular Expression Matching
- Leetcode-10.Regular Expression Matching
- leetcode 10. Regular Expression Matching
- leetcode 10. Regular Expression Matching
- Leetcode 10. Regular Expression Matching
- leetcode 10. Regular Expression Matching
- Leetcode 10. Regular Expression Matching
- leetcode 10. Regular Expression Matching
- LeetCode-10. Regular Expression Matching
- leetcode.10. Regular Expression Matching
- LeetCode 10. Regular Expression Matching
- leetcode 10. Regular Expression Matching
- Leetcode-10. Regular Expression Matching
- 【leetcode】10. Regular Expression Matching
- ubuntu GNUPLOT安装
- java学习-----数组
- rsync核心算法介绍及应用探索
- android 基于jsBridge实现js交互时对webview监听onPageStarted及onPageFinished
- Android6.0权限申请-代码自动插入
- leetcode-10. Regular Expression Matching
- Windows10自适应和交互式toast通知
- Android 秒级编译框架配置过程 --Freeline
- iOS定时器,指定时间后触发。
- ssh传输文件
- ioS应用性能调优的25个建议和技巧(8)
- linux命令持续学习
- Android开发-------设置系统状态栏颜色
- 极光推送 推送处理总结 点击通知跳转