先说一下Brute-Force算法的设计思想吧。将主串S的第一个字符和模式T的第一个字符比较,若相等,则继续逐个比较后续字符。若不等,则从主串S的下一字符起,重新与T的第一个字符比较,直到主串S的一个连续子串字符序列与模式T相等。返回值为S中与T匹配的子序列第一个字符的序号,即匹配成功;否则,匹配失败,返回值-1。
它的算法实现为:
int Find Substr(HString &S,String &t,int start)
{
int i=start,j=0,v;
while(i<S.length&&j<t.length)
{
if(str[i]==t.str[i])
{i++;j++;}
else
{i=i-j+1;j=0;}
}
if(j>t.length-1) v=i-t.length+1;
else v=-1;
return v;
}
OJ上练习:
Binary String Matching
时间限制:
3000 ms | 内存限制:
65535 KB
难度:
3
-
描述
-
Given two strings A and B, whose alphabet consist only ‘0’ and ‘1’. Your task is only to tell how many times does A appear as a substring of B? For example, the text string B is ‘1001110110’ while the pattern string A is ‘11’, you should output 3, because the pattern A appeared at the posit
-
输入
- The first line consist only one integer N, indicates N cases follows. In each case, there are two lines, the first line gives the string A, length (A) <= 10, and the second line gives the string B, length (B) <= 1000. And it is guaranteed that B is always longer than A. 输出
- For each case, output a single line consist a single integer, tells how many times do B appears as a substring of A. 样例输入
-
3 11 1001110110 101 110010010010001 1010 110100010101011
样例输出
-
3 0 3
来源
- 网络 上传者
- naonao
AC代码:
#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
int main()
{
int N;// 定义输入数据的组数;
cin>>N;
char firstChar[12],secondChar[1002]; //定义二个字符数组分别用来存储二个字符串;
while(N--)
{
memset(firstChar,'\0',sizeof(firstChar));
memset(secondChar,'\0',sizeof(secondChar)); // 在用这二个字符数组以前一定要先做置‘\0’的操作;
scanf("%s",firstChar);
scanf("%s",secondChar); // 字符串的录入;
int sum=0; // 用来记录相同的次数;
int i=0;// 用来作为第一个字符串的下标值;
int j=0;// 用来作为第二个字符串的下标值;
int firstLen=(int)strlen(firstChar);
int secondLen=(int)strlen(secondChar);
while(i<firstLen&&j<secondLen)
{
if(firstChar[i]==secondChar[j])
{
i++; j++;
if(i==firstLen)
{ sum++; i=0;j=j-firstLen+1;}
}
else
{
j=j-i+1; i=0;
}
}
cout<<sum<<endl;
}
// system("pause");
return 0;
}