44. Wildcard Matching

Problem:

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 letters a-z.
  • p could be empty and contains only lowercase letters a-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

思路

用DP算法。建立一个数组dp[s.len+1][p.len+1],其中dp[i][j]表示s的前i个字符与p的前j个字符是否匹配,dp[0][0]表示空字符与空字符匹配,dp[s.len][p.len]表示s与p是否匹配。更新的关键在于判断p[j] == '*'是否成立。如果成立,则dp[i][j] = dp[i-1][j] || dp[i][j-1](这一步可以自己在纸上验证),如果不成立,那就按照正常的规则判断是否匹配。判断p[j-1] == '?' || p[j-1] == s[i-1],若成立,说明对应位匹配,则dp[i][j] = dp[i-1][j],否则,不匹配,return false。

Solution (C++):

bool isMatch(string s, string p) {
    int s_len = s.size(), p_len = p.size(), i, j;
    if (!p_len)  return s_len == 0;
    vector<vector<bool>> dp(s_len+1, vector<bool>(p_len+1));
    
    dp[0][0] = true;
    for (int j = 1; j <= p_len; ++j) dp[0][j] = dp[0][j-1] && p[j-1] == '*';
    //i, j分别对应s于p的第i个和第j个字符,即s[i-1]和p[j-1]
    for (i = 1; i <= s_len; ++i) {
        for (int j = 1; j <= p_len; ++j) {
            if (p[j-1] == '*') dp[i][j] = dp[i][j-1] || dp[i-1][j];
            else if (p[j-1] == '?' || p[j-1] == s[i-1]) dp[i][j] = dp[i-1][j-1];
        } 
    }
    return dp[s_len][p_len];
}

性能

Runtime: 100 ms  Memory Usage: 13.6 MB

相关链接如下:

知乎:littledy

欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/dysjtu1995/p/12286412.html