Hdu_2585 Hotel(递归)

来源:互联网 发布:3dmax有没有mac版 编辑:程序博客网 时间:2024/05/18 01:24

题意:

字符串的模糊匹配。给出一个原始串,里面包含字母、‘?‘(代表一个字母)以及‘*’(代表零个或多个字母)。然后给出多个匹配串,问最终可以匹配成功的有多少个。

思路:

最开始的时候想贪心的写出一个验证函数来每次检测是否匹配,但是遇到“*s”匹配“sas”的情况不好写,因为不知道拿哪一个s去匹配。参考了网上的思路用递归去写这个函数,思路也比较清晰。递归的思路可以这么想,就是上面的那种情况导致直接贪心不好写,因为‘*’可以匹配任意长度的串,所以此时可以用不同的子串去匹配,只要有一个匹配成功就算是成功,这样的话想到用递归去写就很自然了。

代码实现:

#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>using namespace std;const int MAX = 52;int N;int res;int len1,len2;char mod[MAX];char test[MAX];bool check(int pos1,int pos2);int main(){    while( scanf("%s",mod) != EOF ){        res = 0;        scanf("%d",&N);        for( int t = 0; t < N; t++ ){            scanf("%s",test);            len1 = strlen(mod);            len2 = strlen(test);            if( check(0,0) == true ){                res++;            }        }        printf("%d\n",res);    }    return 0;}bool check(int pos1,int pos2){    if( pos1==len1 && pos2==len2 ){        return true;    }    else if( mod[pos1] == '*' ){        //一个*匹配零个到任意多个        for( int i = pos2; i <= len2; i++ ){            if( check(pos1+1,i) == true ){                return true;            }        }        return false;    }    else if( mod[pos1] == '?' ){        return check(pos1+1,pos2+1);    }    else{        if( mod[pos1] == test[pos2] ){            return check(pos1+1,pos2+1);        }        else{            return false;        }    }}


0 0
原创粉丝点击