题解 | #记票统计#
字符串通配符
http://www.nowcoder.com/practice/43072d50a6eb44d2a6c816a283b02036
动态规划解法。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool ismatch(char a, char b){
if (a >= 'A' && a <= 'Z'){
a += 32;
}
if (b >= 'A' && b <= 'Z'){
b += 32;
}
return a == b;
}
bool isvalid(char a){
return (a >= 'A' && a <= 'Z') || (a >= 'a' && a <= 'z') || (a >= '0' && a <= '9');
}
int main(){
string s, t;
while (cin >> t >> s){
int len_1 = s.size(), len_2 = t.size();
vector<vector<int>> dp(len_1 + 1, vector<int>(len_2 + 1, 0));
dp[0][0] = 1;
bool flag = false;
for (int i = 0; i <= len_1; i++){
for (int j = 1; j <= len_2; j++){
if (t[j - 1] != '*'){
if (i > 0 && (ismatch(s[i - 1],t[j - 1]) || (t[j - 1] == '?' && isalpha(s[i - 1])))){
dp[i][j] = dp[i - 1][j - 1];
}
}else if (t[j - 1] == '*'){
dp[i][j] |= dp[i][j - 1];
if (j == 1) dp[i][j] = 1;
for (int k = 1; k < i; k++){
if (j >= 2 && (ismatch(s[k - 1], t[j - 2]) || t[j - 2] == '?')){
dp[i][j] |= dp[k][j];
}
}
}else{
flag = true;
break;
}
if (flag) break;
//printf("dp[%d][%d] = %d\n", i, j, dp[i][j]);
}
}
if (flag) {
cout << "false" << endl;
continue;
}
if (dp[len_1][len_2]) cout << "true" << endl;
else cout << "false" << endl;
}
return 0;
} 