【考研-数据结构】串
串(大总结)
#include <iostream>
#define MaxSize 20
using namespace std;
typedef struct SString
{
char ch[MaxSize];
int length;
}SString;
int StrLength(SString S) {
return S.length;
}
bool ClearString(SString& S) {
S.length = 0;
return true;
}
int StrCompare(SString S, SString T) {
for (int i = 1; i <= S.length && i <= T.length; i++) {
if (S.ch[i] != T.ch[i]) return S.ch[i] - T.ch[i];
}
return S.length - T.length;
}
bool SubString(SString& Sub, SString S, int pos, int len) {
if (pos + len - 1 > S.length) return false;
for (int i = pos; i < pos + len; i++) {
Sub.ch[i - pos + 1] = S.ch[i];
}
Sub.length = len;
return true;
}
int Index_01(SString S, SString T) {
int i = 1;
int n = StrLength(S);
int m = StrLength(T);
SString sub;
while (i <= n - m + 1) {
SubString(sub, S, i, m);
if (StrCompare(sub, T) != 0) i++;
else return i;
}
return 0;
}
int Index_02(SString S, SString T) {
int i = 1, j = 1;
while (i <= S.length && j <= T.length) {
if (S.ch[i] == T.ch[j]) {
++i;
++j;
}
else {
i = i - j + 2;
j = 1;
}
}
if (j > T.length) {
return i - T.length;
}
else {
return 0;
}
}
int Index_KMP(SString S, SString T, int next[]) {
int i = 1, j = 1;
while (i <= S.length && j <= T.length) {
if (j == 0 || S.ch[i] == T.ch[j]) {
j++;
i++;
}
else {
j = next[j];
}
}
if (j > T.length) {
return i - T.length;
}
else {
return 0;
}
}
void get_next(SString T, int next[]) {
int i = 1, j = 0;
next[1] = 0;
while (i < T.length) {
if (j == 0 || T.ch[i] == T.ch[j]) {
++i;
++j;
next[i] = j;
}
else {
j = next[j];
}
}
}
void get_nextval(SString T,int nextval[]){
int i = 1;
int j = 0;
while(i<T.length){
if(j == 0||T.ch[i] == T.ch[j]){
++i;
++j;
if(T.ch[i]!=T.ch[j]) nextval[i] = j;
else nextval[i] = nextval[j];
}else{
j = nextval[j];
}
}
}
int main() {
SString S;
S.length = 4;
S.ch[1] = 'a';
S.ch[2] = 'b';
S.ch[3] = 'c';
S.ch[4] = 'd';
SString T;
T.length = 2;
T.ch[1] = 'c';
T.ch[2] = 'd';
cout << Index_02(S, T) << endl;
return 0;
}