LeetCode | Wildcard Matching

题目:

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).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") ? false
isMatch("aa","aa") ? true
isMatch("aaa","aa") ? false
isMatch("aa", "*") ? true
isMatch("aa", "a*") ? true
isMatch("ab", "?*") ? true
isMatch("aab", "c*a*b") ? false

思路:

利用DP的思路来解决问题,时间复杂度为O(mn),空间复杂度也是O(mn)。但是实际上我们只需要考虑上一步与这一步的结果,所以空间复杂度可以压缩为O(n),即保存两步结果即可。

为了减少时间开销,可以首先初略地比较一下两个字符串的长度。

代码:

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int n = str_len(s);
        int m = str_len(p);
        
        bool dp[2][m+1];
        
        int valid = 0;
        dp[0][0] = true;
        for(int j = 1; j< m+1; j++)
        {
            if(p[j-1] == '*')
            {
                dp[0][j] = dp[0][j-1];
            }
            else
            {
                valid++;
                dp[0][j] = false;
            }
        }
        if(valid > n)
        {
            return false;
        }
        
        for(int i = 1; i < n+1; i++)
        {
            if(i == 1)
            {
                dp[0][0] = true;
                dp[1][0] = false;
            }
            else
            {
                dp[0][0] = false;
                dp[1][0] = false;
            }
                
            for(int j = 1; j <m+1; j++)
            {
                if(s[i-1] == p[j-1])
                {
                    dp[i%2][j] = dp[(i-1)%2][j-1];
                }
                else if(p[j-1] == '?')
                {
                    dp[i%2][j] = dp[(i-1)%2][j-1];
                }
                else if(p[j-1] == '*')
                {
                    dp[i%2][j] = (dp[(i-1)%2][j-1] || dp[(i-1)%2][j] || dp[i%2][j-1]);
                }
                else
                {
                    dp[i%2][j] = false;
                }
            }
        }
        
        return dp[n%2][m];
    }
    
    int str_len(const char * c)
    {
        int len = 0;
        while(c[len] != '\0')
        {
            len++;
        }
        
        return len;
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11905181
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞