Given an input string (s
) and a pattern (p
), implement wildcard pattern matching with support for '?'
and '*'
.
'?' 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 lettersa-z
.p
could be empty and contains only lowercase lettersa-z
, and characters like?
or*
.
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
AC code:
class Solution { public: bool isMatch(string s, string p) { int sp = 0; int pp = 0; int match = 0; int start = -1; while (sp < s.length()) { if (pp < p.length() && (s[sp] == p[pp] || p[pp] == '?')) { sp++; pp++; } else if (pp < p.length() && p[pp] == '*') { start = pp; match = sp; pp++; } else if (start != -1) { pp = start + 1; match++; sp = match; } else return false; } while (pp < p.length() && p[pp] == '*') { pp++; } return pp == p.length(); } };
Runtime: 24 ms, faster than 88.38% of C++ online submissions for Wildcard Matching.
2021-05-05 23:23:08
44. 通配符匹配
给定一个字符串 (s) 和一个字符模式 (p) ,实现一个支持 '?' 和 '*' 的通配符匹配。
'?' 可以匹配任何单个字符。
'*' 可以匹配任意字符串(包括空字符串)。
两个字符串完全匹配才算匹配成功。
说明:
s 可能为空,且只包含从 a-z 的小写字母。
p 可能为空,且只包含从 a-z 的小写字母,以及字符 ? 和 *。
示例 1:
输入:
s = "aa"
p = "a"
输出: false
解释: "a" 无法匹配 "aa" 整个字符串。
示例 2:
输入:
s = "aa"
p = "*"
输出: true
解释: '*' 可以匹配任意字符串。
示例 3:
输入:
s = "cb"
p = "?a"
输出: false
解释: '?' 可以匹配 'c', 但第二个 'a' 无法匹配 'b'。
示例 4:
输入:
s = "adceb"
p = "*a*b"
输出: true
解释: 第一个 '*' 可以匹配空字符串, 第二个 '*' 可以匹配字符串 "dce".
示例 5:
输入:
s = "acdcb"
p = "a*c?b"
输出: false
思路:匹配串与模式串能否匹配主要有三种情况:
- if s[i] == p[j] || p[j] == '?' => dp[i][j] = dp[i-1][j-1]
- if p[j] == '*' => dp[i][j] = (dp[i-1][j] || dp[i][j-1])
- else dp[i][j] = false
其中,dp[i][j]表示的是s[0-i]与p[0-j]是否能够进行匹配。初始化的时候应该注意:
- dp[0][0] = true;
- dp[i][0] = false; i = 1, 2, ....
- if p[j] == '*' => dp[0][j] = dp[0][j-1]; j = 1, 2, .....
- else dp[0][j] = false;
Code:
class Solution { public: bool isMatch(string s, string p) { int len1 = s.length(); int len2 = p.length(); vector<vector<bool> > dp(len1+1, vector<bool>(len2+1, true)); for (int i = 1; i <= len1; ++i) dp[i][0] = false; for (int i = 1; i <= len2; ++i) { if (p[i-1] == '*') dp[0][i] = dp[0][i-1]; else dp[0][i] = false; } for (int i = 0; i < len1; ++i) { for (int j = 0; j < len2; ++j) { if (p[j] == '?' || s[i] == p[j]) { dp[i+1][j+1] = dp[i][j]; } else if (p[j] == '*') { dp[i+1][j+1] = (dp[i][j+1] || dp[i+1][j]); } else { dp[i+1][j+1] = false; } } } return dp[len1][len2]; } };