<span style="font-size:18px;">/*LeetCode WildCard matching
* 题目:给定一个目标串和一个匹配串,判定是否能够匹配
* 匹配串中的定义:字符————>字符,*————>0个、1个或者多个字符,?——————>对应任意一个字符
* 思路:动态规划:*:dp[i][j] = dp[i][j-1] || dp[i-1][j]
* ? || s[i] == p[i] :dp[i][j] = dp[i-1][j-1]
*/
package javaTrain;
public class Train23 {
public boolean isMatch(String s, String p) {
int len_s = s.length();
int len_p = p.length();
char[] sArray = new char[len_s];
char[] pArray = new char[len_p];
sArray = s.toCharArray();
pArray = p.toCharArray();
boolean dp[][] = new boolean[500][500]; //用于记录每个子问题的解
int lens = 0;
if(len_p != 0){
for(int i = 0;i < len_p;i++)
if(pArray[i] != '*') lens++;
}
if(lens > len_s) return false;
dp[0][0] = true; //两个串都是空的for
for(int j = 1;j <= len_p;j++){
if(dp[0][j-1] && pArray[j-1] == '*') dp[0][j] = true;
for(int i = 1;i <= len_s;i++){
if(pArray[j-1] == '*') dp[i][j] = dp[i][j-1] || dp[i-1][j];
else if(pArray[j-1] == '?'||pArray[j-1] == sArray[i-1]) dp[i][j] = dp[i-1][j-1];
else dp[i][j] = false;
}
}
return dp[len_s][len_p];
}
}
</span>
【LeetCode】Wildcard Matching 串匹配 动态规划
最新推荐文章于 2020-04-27 14:52:34 发布
