【数据结构与算法】暴力匹配子串-C语言版

/*
Created by justin on 2/3/24.
Contact me by [email protected]
*/
#include "stdio.h"
#include "stdlib.h"
#include

typedef struct String {
    char *data;
    int len;
} String;

String *initString() {
    String *s = (String *) malloc(sizeof(String));
    s->data = NULL;
    s->len = 0;
    return s;
}

void stringAssign(String *s, char * data) {
    if (s->data) {
        // 防止出现脏数据
        free(s->data);
    }
    s->len = strlen(data);
    s->data = (char *) malloc((s->len + 1) * sizeof(char));//为字符串分配内存
    strcpy(s->data, data);
}

void printString(String *s) {
    for (int i = 0; i < s->len; ++i) {
        printf(i == 0 ? "%c" : "->%c", s->data[i]);
    }
    printf("\n");
}

void forceMatch(String *master, String *sub) {
    int i = 0, j = 0;
    while (i < master->len && j < sub->len) {
        if (master->data[i] == sub->data[j]) {
            i++;
            j++;
        } else {
            i = i - j + 1;
            j = 0;
        }
    }
    if (j == sub->len) {
        printf("force match success. \n");
    } else {
        printf("force match fail.\n");
    }
}

int main(int argc, char *argv[]) {
    String *s = initString();
    String *s1 = initString();
    stringAssign(s, argv[1]);
    stringAssign(s1, argv[2]);
    printString(s);
    printString(s1);
    forceMatch(s, s1);
}

暴力匹配子串,

justin@DESKTOP-NIK28BI:~/data_struct_c$ ./ForceMatch ABCDEF  A
A->B->C->D->E->F
A
force match success. 


justin@DESKTOP-NIK28BI:~/data_struct_c$ ./ForceMatch ABCDEF  AE
A->B->C->D->E->F
A->E
force match fail.

这个写法还是很炫的

printf(i == 0 ? "%c" : "->%c", s->data[i]);

你可能感兴趣的:(数据结构与算法,c语言,算法,数据结构)