国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

數(shù)據(jù)結構實驗之串一:KMP簡單應用

2019-11-14 12:33:23
字體:
來源:轉載
供稿:網(wǎng)友

數(shù)據(jù)結構實驗之串一:KMP簡單應用 Time Limit: 1000MS Memory Limit: 65536KB

PRoblem Description 給定兩個字符串string1和string2,判斷string2是否為string1的子串。

Input 輸入包含多組數(shù)據(jù),每組測試數(shù)據(jù)包含兩行,第一行代表string1(長度小于1000000),第二行代表string2(長度小于1000000),string1和string2中保證不出現(xiàn)空格。

Output 對于每組輸入數(shù)據(jù),若string2是string1的子串,則輸出string2在string1中的位置,若不是,輸出-1。

Example Input abc a 123456 45 abc ddd

Example Output 1 4 -1

Hint

Author cjx

以下為accepted代碼

#include <stdio.h>#include <string.h>#include <stdlib.h>#define MAXN 1000004int next[MAXN];void get_next(char *p){ int i = 0, j = -1; int len = strlen(p); next[0] = -1; while(i < len-1) { if(j == -1 || p[i] == p[j]) { i++; j++; next[i] = j; } else j = next[j];//失配時j的值 }}int kmp(char *s, char *p){ int i = 0, j = 0; int len1 = strlen(s); int len2 = strlen(p); memset(next, 0, sizeof(next)); get_next(p); while(i < len1 && j < len2) { if(j == -1 || s[i] == p[j]) { i++; j++; } else j = next[j];//失配時str2回溯的值 } if(j >= len2) return i-len2+1; else return -1;}int main(){ char s[MAXN], p[MAXN]; while(scanf("%s %s", s, p) != EOF) { printf("%d/n", kmp(s, p)); } return 0;}/***************************************************User name: jk160630Result: AcceptedTake time: 100msTake Memory: 5096KBSubmit time: 2017-02-04 11:09:44****************************************************/

以下為建議參考的代碼,感謝作者的啟迪,謝謝。

#include<bits/stdc++.h> using namespace std; char str1[1000001],str2[1000001]; int next[1000001]; void get_next() { int i=0;//i是next數(shù)組下標 next[0]=-1; int j=-1;//j是模板字符串前后綴長度 while(str2[i]!='/0')//從第二個字符開始,計算next數(shù)組對應的值 { if(j==-1||str2[i]==str2[j])//如果相等,下標后移,前后綴長度加1 { i++; j++; next[i]=j; } else j=next[j];//失配時j的值 } } void kmp() { int i=0,j=0; get_next(); int len1=strlen(str1); int len2=strlen(str2); while(i<len1&&j<len2) { if(j==-1||str1[i]==str2[j]) { i++; j++; } else { j=next[j];//失配時str2回溯的位置 } } if(j>=len2) printf("%d/n",i-len2+1);//輸出第一次匹配時的位置 else printf("%d/n",-1); } int main() { while(cin>>str1>>str2) { kmp(); } return 0; }
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 石首市| 海淀区| 靖州| 凉山| 元阳县| 西峡县| 太白县| 湟中县| 岢岚县| 临江市| 凤城市| 扬州市| 白城市| 江达县| 文昌市| 民乐县| 翁源县| 津南区| 德兴市| 赤水市| 大宁县| 大同市| 浙江省| 绍兴市| 彭泽县| 郎溪县| 梁山县| 新安县| 南溪县| 黔江区| 淮阳县| 绥中县| 巫溪县| 临汾市| 定陶县| 水城县| 巴彦县| 抚远县| 隆尧县| 孟连| 景宁|