Wildcard Matching-LintCode

Judge that two may contain wildcards'?'Does the string match'*'?The matching rules are as follows:

'?'can match any single character.
'*'can match any string (including empty strings).

A match is only successful if two strings match exactly.

The function interfaces are as follows:
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

Using backtracking, the constructor determines whether s and p match at the current location.Given the location m, n,
If p[n] is a letter, if s[m]==p[n], process m+1 and n+1 positions, otherwise return false;
If p[n]='?', any single character can be matched and m+1 and n+1 positions can be processed directly.
If p[n]='*', match 0 or more characters, handle J and n+1 positions (m<=j<=s.size()),
Returns true if the condition is full, false otherwise.
To reduce computational effort, the results of processing m, n locations are stored in the map.

#ifndef C192_H
#define C192_H
using namespace std;
class Solution {
    * @param s: A string
    * @param p: A string includes "?" and "*"
    * @return: is Match?
    bool isMatch(string &s, string &p) {
        // write your code here
        map<pair<int, int>, bool> map;//Use map to store calculated data and reduce computational load
        return helper(s, p, 0, 0,map);
    bool helper(string &s, string &p, int m, int n,map<pair<int,int>,bool> &map)
        pair<int, int> pairVal = make_pair(m, n);
        if (map.find(pairVal) != map.end())
            return map[pairVal];
        if (m >= s.size() && n == p.size())//Set Termination Conditions
            return true;
        else if (m < s.size() && n < p.size())
            if (isalpha(p[n]))            //If the element in p is a letter, directly determine whether it is equal to s[m]
                if (p[n] == s[m])
                    return helper(s, p, m + 1, n + 1,map);
                    map[pairVal] = false;
                    return false;
            else if (p[n] == '?')         //The element in p is'?', which can match any single character to process the next bit directly
                return helper(s, p, m + 1, n + 1,map);
            else                          //The element in p is'*', and the loop determines if there is a condition that meets the criteria
                bool flag = false;
                for (int i = m; i <= s.size(); ++i)
                    flag = flag || helper(s, p, i, n + 1,map);
                map[pairVal] = flag;
                return flag;
        //p[n] can only be'*'at this time
        else if (m >= s.size() && n < p.size())
            for (int j = n; j < p.size(); ++j)
                if (p[j] != '*')
                    return false;
            return true;
            return false;

Posted on Mon, 04 May 2020 12:16:07 -0400 by Pie