Problem Description
给定两个字符串string1和string2,判断string2是否为string1的子串。
Input
输入包含多组数据,每组测试数据包含两行,第一行代表string1(长度小于1000000),第二行代表string2(长度小于1000000),string1和string2中保证不出现空格。
Output
对于每组输入数据,若string2是string1的子串,则输出string2在string1中的位置,若不是,输出-1。
Example Input
abc
a
123456
45
abc
ddd
Example Output
1
4
-1
Hint
这道题的时间和内存限制都是一般题目的限制,所以我觉得不用kmp也可能会过,不出意料,果然AC了。
下面这个方法是用了 strstr() 函数
strstr是一种函数,从字符串str1中查找是否有符串str2,如果有,从str1中的str2位置起,返回str1的指针,如果没有,返回null。这是360百科对strstr函数的说明。
特别注意的是,这个函数返回的是指针。
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
char s1[1000010],s2[1000010];
int main(){
while((scanf("%s%s",s1,s2))!=EOF){
char *ch=strstr(s1,s2);
if(ch=='\0')
cout<<"-1"<<endl;
else
cout<<ch-s1+1<<endl;
}
}