淘先锋技术网

首页 1 2 3 4 5 6 7

1.全匹配,而不是匹配字符串的一部分

class Solution {public boolean isMatch(String s, String p) {int m = s.length();int n = p.length();boolean[][] f = new boolean[m + 1][n + 1];f[0][0] = true;for (int i = 0; i <= m; ++i) {for (int j = 1; j <= n; ++j) {// 初始化(0,0)=true 其他值初始化为false// 完善(0,1) (0,2)//     (1,1) (1,2)if (p.charAt(j - 1) == '*') {// p=ca*  s=b false  s[i]!=p[j-1] f[i][j]取决于j-1前的一个字符  f[i][j] = f[i][j - 2]// p=ba*  s=b true   s[i]!=p[j-1] f[i][j]取决于j-1前的一个字符  f[i][j] = f[i][j - 2]//s[i]和p[j-1],实际是s[i-1]和p[j-2]不相等,f[i][j] = f[i][j - 2]f[i][j] = f[i][j - 2];          if (matches(s, p, i, j - 1)) { //因为比实际字符长度多了1行1列,所以这里从s,p中取字符i,j要-1           //s[i]和p[j-1],实际是s[i-1]和p[j-2]相等,f[i][j] = f[i][j] || f[i - 1][j];// 匹配 s 末尾的一个字符,将该字符扔掉,而该组合还可以继续进行匹配;// if条件不满足则f[i][j] = f[i][j - 2]; f[i][j] = f[i][j] || f[i - 1][j];}} else {if (matches(s, p, i, j)) {//因为比实际字符长度多了1行一列,所以这里从s,p中取字符i,j要-1   //情况1 如果p[j-1]='.',s[i-1]不论等啥都和p[i-1]匹配,则s[i-]匹配与p[j-1].//情况2 如果s[i-1]=p[j-1],则s[i-]匹配与p[j-1].//则完整的匹配结果取决于两个字符串前面的部分f[i][j] = f[i - 1][j - 1];//s[i-1]和p[j-1]不相等,f[i][j]为默认值falsef[i][j] = f[i - 1][j - 1];}}}}return f[m][n];}public boolean matches(String s, String p, int i, int j) {if (i == 0) {return false;}if (p.charAt(j - 1) == '.') {return true;}return s.charAt(i - 1) == p.charAt(j - 1);//判断s中的第i-1个字符和p中的第j-1个字符是否相等}
}

 

参考

https://leetcode-cn.com/app/problems/regular-expression-matching/solution/zheng-ze-biao-da-shi-pi-pei-by-leetcode-solution/?isDark=false&rawContent=false?um_chnnl=leetcode?um_from_appkey=5fcda41c42348b56d6f8e8d5

https://leetcode-cn.com/problems/regular-expression-matching/solution/shi-pin-tu-jie-dong-tai-gui-hua-zheng-ze-biao-da-s/