字符串匹配

[编程题|20分] 字符串匹配
时间限制: C/C++ 1秒,其他语言2秒
空间限制: C/C++ 32768K,其他语言65536K
题目描述
牛牛有两个字符串A和B,其中A串是一个01串,B串中除了可能有0和1,
还可能有'?",B中的‘?'可以确定为0或者1。寻找一个字符串T是否在字
符串S中出现的过程,称为字符串匹配。牛牛现在考虑所有可能的字符
串B,有多少种可以在字符串A中完成匹配。
例如:A="00010001",B ="??"
字符串B可能的字符串是"00","01","10","11",只有"11"没有出现在字符
串A中,所以输出3
输入描述:
输入包括两行,第一行一个字符串A,字符串A长度length( 1s le
ngth s 50),A中每个字符都是'0'或者'1'。
第二行一个字符串B,字符串B长度1ength( 1s length s 50 ),
B中的字符包括‘'0','1'和'?'。
 
如图:

这道题目是看到的一道题。难度不大。直接暴力。(ps:如果有大佬知道出处望留言告知一下,Thanks♪(・ω・)ノ)

解题思路:字符串长度<50直接暴力枚举字符串,怎么样都不会超时。kmp来写这题目就显得鸡肋了

理论AC代码:

 1 #include<iostream>
 2 #include<string.h>
 3 #include<string>
 4 #include<algorithm>
 5 #include<stdio.h>
 6 #include<iomanip>
 7 #include<cmath>
 8 #include<map>
 9 using namespace std;
10 map< string , bool > m;
11 int main(){
12     string a,b;
13     cin>>a;
14     cin>>b;
15     int ans=0;
16     if(a.length()<b.length()){
17         cout<<0<<endl;
18     }else{
19         for(int i=0;i<a.length()-b.length()+1;i++){   //我第一份代码这里没有+1,会漏掉最后的一种情况。当时写的太急了,没仔细写
20             int flag=1;
21             string tmp="";
22             for(int t=0,j=i;t<b.length();j++,t++){
23                 tmp=tmp+a[j];
24                 if(a[j]!=b[t]&&b[t]!='?'){
25                     flag=0;
26                     break;
27                 }
28             }
29             if(flag&&!m[tmp]){
30                 ans++;
31                 m[tmp]=true;
32             }
33         }
34         cout<<ans<<endl;
35     }
36     return 0;
37 }
原文地址:https://www.cnblogs.com/ISGuXing/p/8436905.html