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
KMP:
用於在目標串中查找模式串。
如果目標串中有多個模式串,輸出的位置是第一個位置。
1.取得next[]數組的方法:
注意:在SDUT中next[] 數組不能起名爲next,否則 Compile Error;
//改進之前
void get_next(char str2[]) //對模式串進行操作
{
int n = strlen(str2); //模式串的長度
int i=0;
int j=-1;
book[0] = -1;
while(i < n)
{
if(j == -1||str2[i] == str2[j])
{
i++;
j++;
book[i] = j;
}
else
j = book[j];
}
}
//改進後的
void get_next(char str2[])
{
int n = strlen(str2);
int i=0;
int j=-1;
book[0] = -1;
while(i < n)
{
if(j == -1||str2[i] == str2[j])
{
i++;
j++;
if(str2[i] != str2[j])
book[i] = j;
else
book[i] = book[j];
}
else
j = book[j];
}
}
2.KMP函數:查找模式串在目標串中的位置
int KMP(char str1[],char str2[]) //對模式串與目標串同時操作
{
int i = 0;
int j = 0;
int len1 = strlen(str1); //目標串的長度
int len2 = strlen(str2); //模式串的長度
while(i < len1 && j < len2) //兩個串都沒有掃描完進行循環
{
if(j == -1 || str1[i] == str2[j])
{
i++;
j++;
}
else
j = book[j]; //i不變,j後退(即 模式串右滑)
}
if(j >= len2) //當模式串匹配成功
return i-len2+1; //返回模式串在目標串中的位置
else
return -1;
}
代碼
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
char str1[1000005],str2[1000005];
int book[1000005];
void get_next(char str2[])
{
int n = strlen(str2);
int i=0;
int j=-1;
book[0] = -1;
while(i < n)
{
if(j == -1||str2[i] == str2[j])
{
i++;
j++;
if(str2[i] != str2[j])
book[i] = j;
else
book[i] = book[j];
}
else
j = book[j];
}
}
int KMP(char str1[],char str2[])
{
int i = 0;
int j = 0;
int len1 = strlen(str1);
int len2 = strlen(str2);
while(i < len1 && j < len2)
{
if(j == -1 || str1[i] == str2[j])
{
i++;
j++;
}
else
j = book[j];
}
if(j >= len2)
return i-len2+1;
else
return -1;
}
int main()
{
while(scanf("%s",str1)!=EOF)
{
scanf("%s",str2);
get_next(str2);
int p = KMP(str1,str2);
printf("%d\n",p); //p == -1說明查找失敗,否則查找成功
}
return 0;
}