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
#include<stdio.h>
#include<string.h>
int main()
{
int n;
int i,j;
int l1,l2,n1;
char a[15],b[1005];
int sum;
scanf("%d",&n);
while(n--)
{
memset(a,'0',sizeof(a));
memset(b,'0',sizeof(b));
scanf("%s",a);
scanf("%s",b);
l1=strlen(a);
l2=strlen(b);
sum=0;
for(i=0;i<=l2-l1;i++)
{
n1 = 0;
for(j=0;j<l1;j++)
{
if(a[j] == b[i+j])
n1++;
else
break;
}
if(n1==l1)
sum++;
}
printf("%d\n",sum);
}
return 0;
}
在这道题中,有很多问题。(这并不是什么技术性很强得博客,只是我平时刷题时学到的一些很简单的东西。勿喷!)
(1)
在源码中有memset()函数,它的作用是:
1、void *memset(void *s,int c,size_t n)
总的作用:将已开辟内存空间s的首n个字节的值设为值c。
功能:将s所指向的某一块内存中的每个字节的内容全部设置为ch指定的ASCII值,块的大小由第三个参数指定,这个函数通常为新申请的内存做初始化工作。
用法:void *memset(void *s, char ch, unsigned n);
现在我对它的理解是将申明的数组中的东西清空,并分配内存。可能你把它删掉也不会影响输出的结果,但是有的时候考虑到代码安全性的问题,可能它就会有用了。
(2)
gets()函数和scanf()函数的区别
C语言的初学者肯定认为它们没什么区别,我也不例外。
scanf( )函数和gets( )函数都可用于输入字符串,但在功能上有区别。若想从键盘上输入字符串"hi hello",则应该使用__gets__函数。
gets可以接收空格;而scanf遇到空格、回车和Tab键都会认为输入结束,所有它不能接收空格。
char string[15]; gets(string); /*遇到回车认为输入结束*/
scanf("%s",string); /*遇到空格认为输入结束*/
所以在输入的字符串中包含空格时,应该使用gets输入。
scanf和gets获取字符串时的区别
在C语言中,能构获取字符串的函数至少有两个:
1.scanf()
所在头文件:stdio.h
语法:scanf("格式控制字符串",变量地址列表);
接受字符串时:scanf("%s",字符数组名或指针);
2.gets()
所在头文件:stdio.h
语法:gets(字符数组名或指针);
两者在接受字符串时:
1.不同点:
scanf不能接受空格、制表符Tab、回车等;
而gets能够接受空格、制表符Tab和回车等;
2.相同点:
字符串接受结束后自动加'\0'。
例1:
#include <stdio.h>
main()
{
char ch1[10],ch2[10];
scanf("%s",ch1);
gets(ch2);
}
依次键入asd空格fg回车,asd空格fg回车,则ch1="asd\0",ch2="asd fg\0"。
例2:
#include <stdio.h>
main()
{
char ch1[10],ch2[10],c1,c2;
scanf("%s",ch1);
c1=getchar();
gets(ch2);
c2=getchar();
}
依次键入asdfg回车,asdfg回车,则ch1="asdfg\0",c1='\n',ch2="asdfg\0",c2需输入。
scanf :当遇到回车,空格和tab键会自动在字符串后面添加'\0',但是回车,空格和tab键仍会留在输入的缓冲区中。
gets:可接受回车键之前输入的所有字符,并用'\n'替代 '\0'.回车键不会留在输入缓冲区中
gets()用到读取字符串,用回车结束输入
scanf()可以读取所有类型的变量
我在写的时候,就是因为把scanf()用成gets(),导致输出一直出错。
(3
)算法
这道题的算法挺简单的,但是我还是要写一写。
strlen()函数先算出字符串的长度,第一for循环是将 l2 的元素遍历一遍,每次 i 自增1。第二·个for循环,是在不超过 l1 字符串的长度的基础上,让 l2 的字符串中有 l1 个单位数量的元素 一 一 与 l1 中的元素相比较,如果是相同的话,sum自增。(感觉跟冒泡排序的那个算法原理比较像!)