The problem is https://leetcode.com/problems/wildcard-matching/
I wrote the code with recursion and optimize with memoization. but it occurs 'time limit exceeded'. why does this??
int memo[2000][2000];
int check(char* s, char* p, int sIdx, int pIdx){
for (;s[sIdx]!=0&&p[pIdx]!=0;sIdx++,pIdx++){
if (s[sIdx]!=p[pIdx]&&p[pIdx]!='?'){
if (p[pIdx]=='*'){
while (p[++pIdx]=='*') {}
if (p[pIdx]==0){
return 1;
}
for (;s[sIdx]!=0;sIdx++){
if (s[sIdx]==p[pIdx]||p[pIdx]=='?'){
if (memo[sIdx+1][pIdx+1]==1) return memo[sIdx+1][pIdx+1];
if (memo[sIdx+1][pIdx+1]==-1){
if (memo[sIdx+1][pIdx+1] = check(s, p, sIdx+1, pIdx+1)) return 1;
}
}
}
return 0;
}
else{
return 0;
}
}
}
if (s[sIdx]==0&&p[pIdx]==0) {
return 1;
}
else if (s[sIdx]==0) {
while (p[pIdx]!=0) {
if (p[pIdx++]!='*'){
return 0;
}
}
return 1;
}
else{
return 0;
}
}
bool isMatch(char* s, char* p) {
for(int i = 0; i < 2000; i++) {
for(int j = 0; j < 2000; j++) memo[i][j] = -1;
}
return check(s,p,0,0);
}
Even before optimization with memoization, it passes about 1,000 testcases, but after, rather it passes about 600 testcases. I don't know what happens.
Your code is overcomplicated for this problem. At each step, you only need to attempt to match one character instead of iterating to check for all possible matches.
Let us break this down into cases for a dynamic programming solution with
O(|s||p|)time complexity (where|s|indicates the length of the strings).Trivial cases:
If there are no characters left in the pattern, then it can only match if the string to match against is itself empty.
If there are no more characters left in the string, then it can only match if the rest of the pattern consists of only asterisks. We can rewrite this as the current character of the pattern being an asterisk and the rest of the pattern also matching.
Other cases:
If the first character of the string and pattern match or the pattern starts with
?, then we just match the rest of the string against the rest of the pattern.If the first character of the pattern is
*, it can either match nothing or the first character of the string, with the possibility of matching more.Otherwise, there is no match.