zoukankan      html  css  js  c++  java
  • KMPmatch 字符串模式匹配

    O(m+n)

    计算后缀数组时,子串进行的也是模式匹配。

    /* KMP match */
    # include <stdio.h>
    # include <string.h>
    # include <stdlib.h>

    /* P in T */
    int KMPmatch(char *T, char *P)
    {
    int n, m;
    int i, j, k, *next;

    n = strlen(T);
    m = strlen(P);

    next = (int *)malloc((m-1)*sizeof(int));
        /* compute postfix : next[] */
    next[0] = -1;
    k = -1;
    for (i = 1; i < m; ++i)
    {
    while (k>=0 && P[k+1]!=P[i])
    k = next[k];
    if (P[k+1] == P[i]) ++k;
    next[i] = k;
    }

    /*
    for (i=0; i<m; ++i)
    printf("%d ", next[i]+1);
    putchar('\n');
    */

    /* pattern match */
    i = -1;
    for (j = 0; j < n; ++j)
    {
    while (i>=0 && P[i+1]!=T[j])
    i = next[i];
    if (P[i+1] == T[j]) ++i;
    if (i == m-1) return (j-m+1);
    /*
    if (i == m-1)
    {
    printf("Pattern occurs with shift: %d\n", j-m+1);
    i = next[i];
    }
    */
    }

    return -1;
    }

    int main()
    {
    int i;

    i = KMPmatch("Heababababcaf", "ababababca");
    printf("index in T: %d\n", i);

    return 0;
    }

    strstr的用法:

    /* strstr */
    # include <stdio.h>
    # include <string.h>
    int main()
    {
    char T[] = "Hello, world";
    char P[] = "ello, ";
    char *ptr;

    ptr = strstr(T, P);
    if (ptr != NULL) printf("%d %c\n", ptr-T, *ptr);
    else printf("dismatch\n");

    return 0;
    }



  • 相关阅读:
    scp 跨服务器传数据
    Mongo启动失败解决方案
    centos7 NET模式配置虚拟机
    centos7虚拟机配置桥接模式
    Linux centos7 查看cpu 磁盘 内存使用情况
    centos7修改时间和时区
    fiddler培训
    docker学习笔记
    docker-ce安装官翻
    Nginx+Tomcat简单负载均衡
  • 原文地址:https://www.cnblogs.com/JMDWQ/p/2360539.html
Copyright © 2011-2022 走看看