Given an input string (s)
and a pattern (p)
, implement wildcard pattern matching with support for '?'
and '*'
.
给定一个字符串 (s)
和一个字符模式 (p)
,实现一个支持 '?'
和 '*'
的通配符匹配。
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
'?' 可以匹配任何单个字符。
'*' 可以匹配任意字符串(包括空字符串)。
The matching should cover the entire input string (not partial).
两个字符串完全匹配才算匹配成功。
Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like ? or *.
说明:
s 可能为空,且只包含从 a-z 的小写字母。
p 可能为空,且只包含从 a-z 的小写字母,以及字符 ? 和 *。
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
题目分析
我们建立一个dp[i][j]
数组,表示s串中的s[0]
到s[i-1]
与 p串中的p[0]
到p[j-1]
的匹配情况,只有true 或者 false 两种情况。之后只需要写出状态转移方程,并根据方程填满数组,返回数组最后一个元素即可。
动态规划
动态规划一般有以下几个步骤:
建立二维dp数组 ->初始化数组 ->根据状态转移方程填满数组 ->返回数组的最后一个元素,就是我们所求的答案
状态转移方程:
dp[i][j] = dp[i-1][j-1]
if s[i-1] == p[j-1] || p[j-1] == '?'
dp[i][j] = dp[i][j-1] || dp[i-1][j]
if p[j-1] == '*'
C++
//state equation :
// dp[i][j] = dp[i-1][j-1] if s[i-1] == p[j-1] || p[j-1] == '?'
// dp[i][j] = dp[i][j-1] || dp[i-1][j] if p[j-1] == '*'
class Solution {
public:
bool isMatch(string s, string p) {
int m = s.size();
int n = p.size();
bool dp[m + 1][n + 1];
memset(dp,0,sizeof(dp));
dp[0][0] = true;
for (int i = 1; i <= n; i++) {
dp[0][i] = dp[0][i - 1] && p[i - 1] == '*';
}
//dp
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (s[i - 1] == p[j - 1] || p[j - 1] == '?') {
dp[i][j] = dp[i - 1][j - 1];
} else if (p[j - 1] == '*') {
dp[i][j] = dp[i][j - 1] || // * 当作空串使用
dp[i - 1][j];// * 当作任意字符串使用
}
}
}
return dp[m][n];
}
};
动态规划类似的题目:
LeetCode 5. Longest Palindromic Substring
LeetCode 10. Regular Expression Matching (动态规划) C++