/*
* 10. Regular Expression Matching
QuestionEditorial Solution My Submissions
Total Accepted: 86843
Total Submissions: 387233
Difficulty: Hard
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
Hide Company Tags Google Uber Airbnb Facebook Twitter
Hide Tags Dynamic Programming Backtracking String
Hide Similar Problems (H) Wildcard Matching
*/
package dp;
public class RegularExpressMatch {
public boolean isMatch(String s, String p) {
// 参考视频 https://www.youtube.com/watch?v=l3hda49XcDE
int M = s.length(), N = p.length();
boolean[][] T = new boolean[M + 1][N + 1];
T[0][0] = true;
char[] pattern = p.toCharArray();
char[] str = s.toCharArray();
// deal with patterns like a*, a*b, a*b*c
for (int j = 1; j < T[0].length; j++) {
if (pattern[j - 1] == '*') {
T[0][j] = T[0][j - 2];
}
}
for (int i = 1; i < T.length; i++) {
for (int j = 1; j < T[0].length; j++) {
if (pattern[j - 1] == '.' || str[i - 1] == pattern[j - 1]) {
T[i][j] = T[i - 1][j - 1];
} else if (pattern[j - 1] == '*') {
T[i][j] = T[i][j - 2];
if (pattern[j - 2] == '.' || pattern[j - 2] == str[i - 1]) {
T[i][j] = T[i][j] | T[i - 1][j];
}
} else {
T[i][j] = false;
}
}
}
return T[M][N];
}
public static void main(String[] args) {
RegularExpressMatch rem = new RegularExpressMatch();
String str = "aab", pattern = "c*a*b";
System.out.println(rem.isMatch(str, pattern)); // true
}
}
10. Regular Expression Matching
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Implement regular expression matching with support for '....
- 各位看官别怪我少见多怪,连这么经典的题目都要拿出来说一遍。但是对于字符串和DP同时相关的题目我是真不熟练。。。这不...
- Implement regular expression matching with support for '....
- 题设 要点 二维数组动态规划DP[][] 首先,按照之前解回文串的思路,这种题可以考虑采用动态规划的方法来做。我们...
- Implement regular expression matching with support for '....