【数据结构与算法】44. Wildcard Matching

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

题目说明:外卡匹配,使用动态规划的思路。外卡匹配和正则匹配的最大不同就是外卡匹配中星号可以单独存在。

创建匹配数组(用vector<vector<bool>> match表示),大小分别为s.length()+1和p.length()+1,数组内容match[i][j]表示s中s[i]之前(包含s[i])和p中p[j]之前(包含p[j])是否匹配。

动态规划的初始状态match[0][0]=true;match[i][0]=false;math[0][j]=match[0][j-1] while p[j]='*'

AC代码:

class Solution {
public:
    bool isMatch(string s, string p) {
        int m = s.length();
        int n = p.length();
        
        vector<vector<bool>> match(m+1 ,vector<bool>(n+1, false));
        match[0][0] = true;
        for (int pi = 1; pi <= n; ++pi)
        {
            if (p[pi-1] == '*')
            {
                match[0][pi] = match[0][pi-1];
            }
        }
        
        for (int si = 1; si <= m; ++si)
        {
            for (int pi = 1; pi <= n; ++pi)
            {
                if (s[si-1] == p[pi-1] || p[pi-1] == '?')
                {
                    match[si][pi] = match[si-1][pi-1];
                }
                else if (p[pi-1] == '*')
                {
                    match[si][pi] = match[si-1][pi] || match[si][pi-1];
                }
            }
        }
        return match[m][n];
    }
};

  

posted @ 2018-05-03 14:15  stay_heart  阅读(172)  评论(0编辑  收藏  举报