[leetcode] Wildcard Matching


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

Dynamic programming approach. O(p*s*s) p is the length of patten, s is the length of string.

Time Limit Exceeded. I don’t think out better solution so far.

class Solution {
public:
    bool isMatch(string s, string p) {
        //dp[i][j] stores whether patten[0~i] can match string[0~j - 1] dp[i][0] means whether patten[0~i] can match an empty string
        //dp[i][j] = dp[i - 1][k] && isMatch(p[i], s[k+1~j]), k = 0, 1, 2, ..., j , when k is j , s[k+1~j] means an empty string
        if(p.size() == 0 && s.size() == 0) return true;
        if(p.size() == 0) return false;//p.size() == 0 && s.size() > 0
        bool dp[p.size()][s.size() + 1];
        //memset(dp, false, sizeof(dp));
        for(int i = 0; i < s.size() + 1; i++){
            //initialize
            char patten = p[0];
            dp[0][i] = isMatchChar(s.substr(0, i), patten);
        }
        for(int i = 1; i < p.size(); i++){
            for(int j = 0; j < s.size() + 1; j++){
                //populate the dp array
                for(int k = 0; k <= j; k++){
                    dp[i][j] = dp[i - 1][k] && isMatchChar(s.substr(k, j - k), p[i]);
                    if(dp[i][j]){
                        break;//
                    }
                }
            }
        }
        return dp[p.size() - 1][s.size()];
    }
    bool isMatchChar(string s, char p){
        if(p == '*') return true;
        if(p == '?' && s.size() == 1) return true;
        if(s.size() == 1 && p == s[0]) return true;
        return false;
    }
};

 

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.