----- Edit by ZhuSenlin HDU
The wildcard matching algorithm is designed. The * number can match any number of characters ,? Can match any character. For example, 12345, 12 *, and 12 *? And 12*4? And so on.
Function prototype: bool match (const char * str, const char * strpattern );
Analysis: use dynamic planning to solve the problem.
This question is similar to that of LCS. Assume that string A [I] represents the first I + 1 substring, and string B [j] represents the first j + 1 substring, then whether A [I] and B [j] can be matched by A [I-1], B [J-1]; A [[I-1], B [j]; and A [I] B [J-1] combined with the characters of the current A [I] and B [j.
A [I] and B [j] matching is equivalent
1. A [I-1] matches with B [J-1] and (A [I] = B [j] | A [I] = * | (A [I] = '? '& B [j]! = '\ 0 '))
2. A [I-1] matches with B [j] and (A [I] = '*')
3. A [I] matches B [J-1] and (A [I] = '*' | (A [I-1] = '*' & (A [] = [i] = B [j] | (A [I] = '? '& B [j]! = '\ 0 '))))
Between any
The Code is as follows:
bool match_string(const char* str, const char* strpattern){int nStr = strlen(str);int nPatt = strlen(strpattern);int** pTable = new int* [nStr+1];for(int k = 0; k <= nStr; k++) {pTable[k] = new int [nPatt+1];memset(pTable[k],0,(nPatt+1)*sizeof(int));}pTable[0][0]=1;for(int i=1; i <= nStr; i++){for(int j=1;j <= nPatt; j++){if(pTable[i-1][j-1] == 1 && (strpattern[j-1] == str[i-1]|| (strpattern[j-1] == '?' && str[i-1] != '\0')|| strpattern[j-1] == '*')){pTable[i][j] = 1;}else if(pTable[i][j-1] == 1 && ((strpattern[j-1] == '*') || (j > 1 && strpattern[j-2] == '*'&&((strpattern[j-1] == '?' && str[i-1] != '\0')||strpattern[j-1] == str[i-1])))) {pTable[i][j] = 1;}else if (pTable[i-1][j] == 1 && strpattern[j-1] == '*') {pTable[i][j] = 1;}}}bool ret = (pTable[nStr][nPatt] == 1 ? true : false);for(int k = 0; k <= nStr; k++)delete [] pTable[k];delete pTable;return ret;}
The test code is as follows:
int main(int argc, char** argv){if(match_string(argv[1],argv[2])){cout << argv[1] << " and " << argv[2] << " matched!" << endl;}elsecout << argv[1] << " and " << argv[2] << " are not matched!" << endl;return 0;}