首页 > 代码库 > 字符串匹配

字符串匹配

2个普通的 暴力求解


/*
 * CreateTime: 2014-09-16 19:48:46
 */
#include <cstdio>
#include <cstring>

int main(void)
{
    char a[100] = "abcacabcccc";
    char b[100] = "cc";

    for(int i = 0; i <= strlen(a) - strlen(b); i++) {
        int ok = 1;
        for(int j = 0; j < strlen(b); j++) {
            if(a[j+i] != b[j]) {
                ok = 0;
                break;
            }
        }
        if(ok) {
            printf("%d\n", i);
            break;
        }
    }

    return 0;
}
/*
 * CreateTime: 2014-09-18 00:02:42
 */
#include <cstdio>
#include <cstring>

int main(void)
{
    char s[100] = "abcacabcccc";
    char p[100] = "cc";

    int i = 0;
    int j = 0;
    while(i < strlen(s) && j < strlen(p)) {
        if(s[i] == p[j]) {
            i++;
            j++;
        } else {
            i = i - j + 1;
            j = 0;
        }
    }
    if(j == strlen(p)) {
        printf("%d\n", i - j);
    } else {
        printf("-1\n");
    }

    return 0;
}

kmp 算法


/*
 * CreateTime: 2014-09-16 19:04:23
 * Gain:
      strlen(s);  返回的是 unsigned 的值,
      如果想用 int i < strlen(s) 等情况的时候,
      必须考虑 i 的值如果是 负数的 情况, 例如是
      -1, 那么 i > strlen(s), 0xff..ff.

      保险的做法是 int len = strlen(s);
      然后再继续.
 */
#include <cstdio>
#include <cstring>

void kmp(char *s, char *p);
void get_next(char *p, int *next);

int main(void)
{
    char a[100] = "abcacabcccc";
    char b[100] = "cc";
    kmp(a, b);

    return 0;
}

void get_next(char *p, int *next) {
    int j = 0;
    int k = -1;
    int p_len = strlen(p);
    next[0] = -1;

    while(j < p_len - 1) {
        if(k == -1 || p[j] == p[k]) {
            ++j;
            ++k;
            if(p[j] != p[k]) {  // k == -1
                next[j] = k;
            } else {            // k != -1  p[j] == p[k]
                next[j] = next[k];
            }
        }
        else {                  // p[j] != p[k]
            k = next[k];
        }
    }
}

void kmp(char *s, char *p) {
    int i = 0;
    int j = 0;
    int s_len = strlen(s);
    int p_len = strlen(p);
    int next[100];

    get_next(p, next);
    while((i < s_len) && (j < p_len)) {
        if(j == -1 || s[i] == p[j]) {
            i++;
            j++;
        } else {
            j = next[j];
        }
    }
    if(j == p_len) {
        printf("%d\n", i - j);
    } else {
        printf("-1\n");
    }
}

字符串匹配