Wildcard Matching
Description
Given an input string (s
) and a pattern (p
), implement wildcard pattern matching with support for '?'
and '*'
where:
'?'
Matches any single character.'*'
Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
- Example 1
Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
- Example 2
Input: s = "aa", p = "*"
Output: true
Explanation:'*' matches any sequence.
- Example 3
Input: s = "cb", p = "?a"
Output: false
Explanation:'?' matches 'c', but the second letter is 'a', which does not match 'b'.
- Example 4
Input: s = "adceb", p = "*a*b"
Output: true
Explanation:The first '*' matches the empty sequence, while the second '*' matches the substring "dce".
- Example 5
Input: s = "acdcb", p = "a*c?b"
Output: false
Constraints:
0 <= s.length, p.length <= 2000
s
contains only lowercase English letters.p
contains only lowercase English letters,'?'
or'*'
.
Solution
心路历程
动态规划(DP)本次结果取决于上次运算的结果。
-
一 判断是否可以用动态规划(最优子结构、重叠或者重复的子问题)
很明显是重叠子问题,可以用DP。
-
二 描述状态或者状态是否可以描述
dp[i][j]表示s[0,i-1](左闭右闭)和p[0,j-1](左闭右闭)的匹配情况,匹配为true,不匹配为false i也就是前i个元素的意思。 由此可知,二维数组维度应该是s.length()+1 和 p.length()+1
-
三 状态转移方程以及初始状态。
1)i 指向的字符和 j 指向的字符相等:两种相等的情况
2)j-1 指向的字符是* 如下三种情况
a) * 对应 s 中 0 个字符,也就是看 s[ 0 , i - 1] 和 p[ 0 , j - 2 ]的匹配情况
b) * 对应 s 中 1 个字符,也就是看 s[ 0 , i - 2] 和 p[ 0 , j - 2 ]的匹配情况
c) * 对应 s 中 2 个字符,也就是看 s[ 0 , i - 2] 和 p[ 0 , j - 1 ]的匹配情况
别人写的代码
class Solution {
public static boolean isMatch(String s, String p) {
// 申请dp[][]表格,dp[i][j]表示 若s(0,i-1)与p(0,j-1)匹配,dp[i][j]=true,否则为false
boolean [][] dp = new boolean [s.length()+1][p.length()+1];
// s与p都为空时,匹配
dp[0][0] = true;
// s为空,p中含有'*'时
for(int j=1;j<(p.length()+1);j++){
if (p.charAt(j-1) == '*')
dp[0][j]=dp[0][j-1] && true;
}
for(int i=1;i<(s.length()+1);i++){
for(int j=1;j<(p.length()+1);j++){
if ((p.charAt(j-1) == s.charAt(i-1)) || (p.charAt(j-1) == '?')){
dp[i][j] = dp[i-1][j-1];
}
//j-1指向*,在dp数组中是第j列
if (p.charAt(j-1) == '*'){
dp[i][j] = dp[i][j-1] || dp[i-1][j] || dp[i-1][j-1];
}
}
}
return dp[s.length()][p.length()];
}
}
Appendix
参考他人文章
https://blog.csdn.net/weixin_39781462/article/details/83182563