LintCode-通配符匹配

判断两个可能包含通配符“?”和“*”的字符串是否匹配。匹配规则如下:

'?' 可以匹配任何单个字符。
'*' 可以匹配任意字符串(包括空字符串)。

两个串完全匹配才算匹配成功。

函数接口如下:
bool isMatch(const char *s, const char *p)

您在真实的面试中是否遇到过这个题?  Yes
样例

一些例子:

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

标签 
Expand  

相关题目 
Expand 

分析:一般两个字符串的问题,基本都可以通过动态规划来解决,可以用dp[i][j]来表示s中前I位和p中前j位的匹配情况,一开始写了个N^3次的解法,也能AC,加了一个辅助数组,优化到N^2

代码:

class Solution {
public:
    /**
     * @param s: A string 
     * @param p: A string includes "?" and "*"
     * @return: A boolean
     */
    bool isMatch(const char *s, const char *p) {
        // write your code here
        int n = strlen(s);
        int m = strlen(p);
        vector<vector<bool> > dp(n+1,vector<bool>(m+1,false));
        vector<vector<bool> > f(n+1,vector<bool>(m+1,false));
        dp[0][0] = true;
        f[0][0]=true;
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
            {
                if(p[j-1]=='?')
                    dp[i][j] = dp[i-1][j-1];
                else if(p[j-1]=='*')
                {
                    if(f[i][j-1]||j==1)
                        dp[i][j]=true;
                }
                else
                {
                    if(s[i-1]==p[j-1])
                        dp[i][j] = dp[i-1][j-1];
                    else
                        dp[i][j] = false;
                }
                f[i][j] = f[i-1][j]|dp[i][j];
            }
            
        }
        return dp[n][m];
    }
};
    原文作者:LintCode题目解答
    原文地址: https://blog.csdn.net/wangyuquanliuli/article/details/47378611
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞