[leetcode]44. Wildcard Matching

链接:https://leetcode.com/problems/wildcard-matching/description/

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


扫描二维码关注公众号,回复: 1000199 查看本文章

用bool型二维数组vvb[i][j]表示s的前i个字符和p的前j个字符是否匹配。

初始值,dp[0][0]为true,dp[0][j]的值取决于p前一个位置是否为‘*’以及前一情况是否匹配。

当p[j]等于‘?’或者s[i]等于p[j]时,则dp[i][j]的值取决于dp[i-1][j-1],即为s的前一位置和p的前一位置是否匹配;

当p[j]等于‘*’时,如果该‘*’可以匹配s中的0个或者k (k=1 ~ n)个字符,分别对应dp[i][j-1],即s的当前位置和p的前一位置是否匹配,以及dp[i-1][j],即s的前一位置和p的当前位置是否匹配。


class Solution {
public:
    bool isMatch(string s, string p) {
        vector<vector<bool>> dp(s.size()+1, vector<bool>(p.size()+1, false));
        dp[0][0] = true;
        
        for(int j=1; j<=p.size(); j++)
        {
            if(p[j-1]=='*')
                dp[0][j] = true;
            else
                break;
        }
        
        for (int i=1; i<=s.size(); i++)
        {
            for (int j=1; j<=p.size(); 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[s.size()][p.size()];

猜你喜欢

转载自blog.csdn.net/xiaocong1990/article/details/80301235