/*
* 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 '....