关闭

KMP算法

197人阅读 评论(0) 收藏 举报
分类:
//============================================================================
// Name        : C++Study.cpp
// Author      : pan
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================


#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include <queue>
#include <stack>
#include <assert.h>
#include <string.h>
using namespace std;


struct String {


char* s = NULL;
int length = 0;


};
void assignString(String* dst, const char* t) {


assert(t!=NULL);
if (dst->s) {
delete dst->s;
}
int len = strlen(t);
dst->s = new char[len + 1];
dst->s[len] = '\0'; ///////这里好好理解下
for (int i = 0; i < len; i++) {
dst->s[i] = t[i];
dst->length++;
}


}
String* concatString(String* s1, String* s2) {


String* s = new String;
s->s = new char[s1->length + s2->length + 1];
s->s[s1->length + s2->length] = '\0';
int i = 0;
while (s1->s[i] != '\0') {
s->s[i] = s1->s[i];
i++;
}
while (s2->s[i] != '\0') {
s->s[i] = s2->s[i];
i++;
}
s1->s = new char[s1->length + s2->length + 1];
i = 0;
while (s->s[i] != '\0') {
s1->s[i] = s->s[i];
// cout << s->s[i];
i++;
}
s1->s[i] = '\0';
delete s->s;
delete s;
return s1;
}


void showString(String* s) {
int i = 0;
while (s->s[i] != '\0') {
cout << s->s[i];
i++;
}
}


int indexSubString(String* src, String* sub) { //求子串的位置
int i = 0, j = 0;
while (i < src->length && j < sub->length) {
if (src->s[i] == sub->s[j]) {
i++;
j++;
} else {
i = i - j + 1;
j = 0;
}
}
if (j == sub->length)
return i - j + 1;


return 0;
}


void getnext(String* pat, int next[]) {
int k = -1;
int j = 0;
next[0] = -1;
int len = strlen(pat->s);
while (j < len) {
if (k == -1 || pat->s[k] == pat->s[j]) {
next[++j] = ++k;
} else {
k = next[k];
}
}
}
int KMP_find(String* obj, String* pat, int next[]) {//KMP算法
int len1 = strlen(obj->s);
int len2 = strlen(pat->s);
int i = 0, j = 0;
while (i < len1 && j < len2) {
if ((j == -1)||(pat->s[j] == obj->s[i])) {
i++;
j++;
} else {
j = next[j];
}
}
if (j > len2) {
return i - j;
}
return -1;
}
int main() {


/* if('\0'==NULL)
{
cout<<"yes";
}*/
String s1, s2;
char* c = "abcdefg";
assignString(&s1, c);
assignString(&s2, "cde");
String* s = concatString(&s1, &s2);
//showString(s);
int next[strlen(c) + 1];
getnext(&s1, next);
KMP_find(&s1, &s2, next);


delete s1.s;
delete s2.s;
delete s->s;


return 0;
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:24397次
    • 积分:1023
    • 等级:
    • 排名:千里之外
    • 原创:79篇
    • 转载:11篇
    • 译文:0篇
    • 评论:0条