Problem 1032 - 找模式串
Time Limit: 1000MS Memory Limit: 65536KB Difficulty:
Total Submit: 644 Accepted: 323 Special Judge: No
Total Submit: 644 Accepted: 323 Special Judge: No
Description
在字符串中查找指定的模式串是一种常见的运算,称为模式匹配。请你编写实现模式匹配的程序。
Input
输入数据的第一行是一个正整数T(0<T≤100),表示有T组测试数据。
每组测试数据有两行:第一行为字符串S(长度不超过128,全部为大写英文字母),第二行为模式串P(长度不超过20)。
每组测试数据有两行:第一行为字符串S(长度不超过128,全部为大写英文字母),第二行为模式串P(长度不超过20)。
Output
对于每组测试数据,在一行上输出一个整数,表示模式串P在字符串S中的位置序号(若出现多次,则输出第一次出现时的位置)。若在字符串S中找不到模式串P,则输出整数-1。
Sample Input
3
ABCDEF
AB
EJBBMSWJPREAEYBM
MBWEJ
DCZRZYFGJVTPWKF
ZYFG
ABCDEF
AB
EJBBMSWJPREAEYBM
MBWEJ
DCZRZYFGJVTPWKF
ZYFG
Sample Output
0
-1
4
-1
4
Hint
/* 读入整数 */
int t;
scanf("%d
",&t); //或者 scanf("%d",&t);
/* 读入串 */
char str[200];
scanf("%s",str); //C格式
cin >> str; //C++格式
Source
8th Xidian University Collegiate Programming Contest(2010.6)
#include<stdio.h>
#include<string.h>
char str[1000],ss[1000];
int find()
{
int len1=strlen(&str[1]),len2=strlen(&ss[1]),i,j;
for (i=1;i+len2-1<=len1;i++)
{
bool flag=true;
for (j=1;j<=len2;j++)
if (str[i+j-1]!=ss[j]) flag=false;
if (flag) return (i-1);
}
return -1;
}
int main()
{
int T;
scanf("%d",&T);
while (T--)
{
memset(str,0,sizeof(str));
memset(ss,0,sizeof(ss));
scanf("%s",&str[1]);
scanf("%s",&ss[1]);
printf("%d
",find());
}
return 0;
}