老師講了狀態轉移方程:
key[1..i] 與 w[1..j] 是否匹配?用狀態f【i】【j】記錄:
f【i】【j】=
f【i-1】【j-1】 if key【i】== ‘?’
f【i-1】【j-1】 && key【i】==w【j】 if key【i】爲字母
f【i-1】【j】|| f【i-1】【j-1】||f【i】【j-1】if key【i】==‘*’
‘*’ 無匹配 匹配一個 匹配>=2;
初始條件很難設置阿,wrong了很多次,不過還好有馬甲~偶也~
主要問題是開始的多個* 可以看作不匹配,這樣造成match【0】【0】= 1不能初始化因爲開始連續多個**造成的移位。
#include<stdio.h>
#include<cstring>
char d[51];
char h[51];
bool match[51][51];
int n;
inline bool check(char *s){
int r = strlen(d),
c = strlen(s),
i, j ;
memset(match, 0, sizeof(match));
match[0][0] = 1;
//下一句初始化是關鍵!eg: *t 1 t
for(i = 1; i<= r; i++) match[i][0] = (d[i-1]=='*') && match[i-1][0];
for(i = 1; i<= r; i++){
for(j = 1; j<= c; j++){
if(d[i-1]=='?')match[i][j] = match[i-1][j-1];
else if(d[i-1]=='*')
match[i][j] = match[i-1][j] ||match[i-1][j-1]|| match[i][j-1];
else match[i][j] = match[i-1][j-1] && (d[i-1]== s[j-1]);
}
}
return match[r][c];
}
int main(){
// freopen("in","r", stdin);
while(scanf("%s", d) != EOF){
scanf("%d", &n);
int cnt =0, i ;
for(i = 0 ; i< n; i++) {
scanf("%s", h);
if(check(h)) cnt++;
}
printf("%d\n", cnt);
}
}