题目
https://leetcode-cn.com/problems/regular-expression-matching
https://leetcode-cn.com/problems/zheng-ze-biao-da-shi-pi-pei-lcof
解法
- 回溯法
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 
 | class Solution {public boolean isMatch(String text, String pattern) {
 if (pattern.isEmpty()) return text.isEmpty();
 boolean first_match = (!text.isEmpty() &&
 (pattern.charAt(0) == text.charAt(0) || pattern.charAt(0) == '.'));
 
 if (pattern.length() >= 2 && pattern.charAt(1) == '*'){
 return (isMatch(text, pattern.substring(2)) ||
 (first_match && isMatch(text.substring(1), pattern)));
 } else {
 return first_match && isMatch(text.substring(1), pattern.substring(1));
 }
 }
 }
 
 | 
- DP
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 
 | class Solution {public boolean isMatch(String text, String pattern) {
 boolean[][] dp = new boolean[text.length() + 1][pattern.length() + 1];
 dp[text.length()][pattern.length()] = true;
 
 for (int i = text.length(); i >= 0; i--){
 for (int j = pattern.length() - 1; j >= 0; j--){
 boolean first_match = (i < text.length() &&
 (pattern.charAt(j) == text.charAt(i) ||
 pattern.charAt(j) == '.'));
 if (j + 1 < pattern.length() && pattern.charAt(j+1) == '*'){
 dp[i][j] = dp[i][j+2] || first_match && dp[i+1][j];
 } else {
 dp[i][j] = first_match && dp[i+1][j+1];
 }
 }
 }
 return dp[0][0];
 }
 }
 
 |