What is the most efficient wildcard string matching algorithm? I am asking only about an idea, it is not necessary to provide actual code.
I\'m thinking that such al
I was looking for a simple wildcard matching algorithm which runs in polynomial time. E.g. this one is simple, but doesn't run in polynomial time when the pattern contains many stars (*): http://www.codeproject.com/Articles/188256/A-Simple-Wildcard-Matching-Function Below is the code which uses dynamic programming to reduce the time complexity to O(n*m) where n is the length of the text and m is the length of the pattern.
#include
#include
#include
using namespace std;
const int UNKNOWN = -1;
const int NOMATCH = 0;
const int MATCHES = 1;
class Wildcard {
string _text;
string _pattern;
vector> _mf;
int F(int n, int m) {
if (_mf[n][m] >= 0) return _mf[n][m];
if (n == 0 && m == 0) {
_mf[n][m] = MATCHES;
return _mf[n][m];
}
if (n > 0 && m == 0) {
_mf[n][m] = NOMATCH;
return _mf[n][m];
}
// m > 0
int ans = NOMATCH;
if (_pattern[m - 1] == '*') {
ans = max(ans, F(n, m-1));
if (n > 0) {
ans = max(ans, F(n - 1, m));
}
}
if (n > 0) {
if (_pattern[m - 1] == '?' || _pattern[m - 1] == _text[n - 1]) {
ans = max(ans, F(n - 1, m - 1));
}
}
_mf[n][m] = ans;
return _mf[n][m];
}
public:
bool match(string text, string pattern) {
_text = text;
_pattern = pattern;
_mf.clear();
for (int i = 0; i <= _text.size(); i++) {
_mf.push_back(vector());
for (int j = 0; j <= _pattern.size(); j++) {
_mf[i].push_back(UNKNOWN); // not calculated
}
}
int ans = F(_text.size(), _pattern.size());
return ans == MATCHES;
}
};