[LeetCode]10. Regular Expression Matching
来源:互联网 发布:python matplotlib安装 编辑:程序博客网 时间:2024/06/10 07:26
Description
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)
Example
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
Discussion
这个问题可以采用动态规划。我们维护一个二位数组dp
。dp[i+1][j+1]
记录s[i]
和p[j]
之前的内容是否匹配。下面是dp
的递推式:
dp初始都为0;
1. 若p和s当前字符匹配:dp[i + 1][j + 1] = dp[i][j];
2. 若p当前为*,且p前一个字符a和s当前字符a匹配,则a*可以是0,1或n个:dp[i + 1][j + 1] = (dp[i + 1][j - 1] || dp[i + 1][j] || dp[i][j + 1]);
3. 若p当前为*,且p前一个字符a和s当前字符b不匹配,则a*只能是0个:dp[i + 1][j + 1] = dp[i + 1][j - 1]。
算法的时间复杂度为O(n^2)。
C++ Code
class Solution {public: bool isMatch(string s, string p) { //由dp[i+1][j+1]来记录s[i]和p[j]之前是否匹配 int dp[s.length() + 1][p.length() + 1]; memset(dp, 0, sizeof(dp)); dp[0][0] = 1; //考虑a*b*c*开头可能为空的情况 for (int i = 1; i < p.length(); i++) { if (p[i] == '*' && dp[0][i-1]) { dp[0][i+1] = 1; } } for(int i = 0; i < s.length(); i++) { for(int j = 0; j < p.length(); j++) { //若p和s当前字符匹配 if(p[j] == s[i] || p[j] == '.') { dp[i + 1][j + 1] = dp[i][j]; } //若p当前为* if(p[j] == '*') { //若p前一个字符a和s当前字符a匹配,则a*可以是0,1或n个 if(p[j - 1] == s[i] || p[j - 1] == '.') { dp[i + 1][j + 1] = (dp[i + 1][j - 1] || dp[i + 1][j] || dp[i][j + 1]); } //若p前一个字符a和s当前字符b不匹配,则a*只能是0个 else { dp[i + 1][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
- MySQL安装配置
- Broadcast Receiver使用
- 建立枚举类型Weekday,假设今日为星期二,计算10天后为星期几。
- HTTP协议(转)
- Leetcode32. Longest Valid Parentheses
- [LeetCode]10. Regular Expression Matching
- Button点击效果
- JVM(PART II)Eden Survivor名称由来
- php中面向对象的封装和继承
- Mybatis——可视化generator工具的介绍
- Servlet与Filter的区别
- 如何在Qt中安装事件过滤器
- 【BZOJ1026】【数位DP】windy数 题解
- 从键盘输入若干个字符,逐个存到磁盘文件data.txt中,直到输入’\n’为止,并将建立的文本文件的内容在存入文件的同时,在屏幕上显示出来: