zoukankan      html  css  js  c++  java
  • 字符串问题 【微软面试100题 第八十五题】

    题目要求

      已知一个字符串,比如adserwsde,寻找其中的一个子字符串比如sde的个数,如果没有就返回0,有的话返回子字符串的个数。

    题目分析

      对KMP算法稍加修改一下就行:在应该返回字符串的地方进行计数。

    代码实现

    #include <stdio.h>
    #include <string.h>
    
    void compute_prefix(int *next, char *p);
    int kmp_match(char *text, char *p, int *next);
    
    int main()
    {
        int   next[101], n;
        char  *p = "caca" ;
        char  *text = "abcacacaca" ;
    
        compute_prefix(next, p);
        printf( "num = %d
    ",kmp_match(text, p, next));
    
        return 0;
    }
    void compute_prefix(int *next, char *p)
    {
        int         i, n, k;
    
        n = strlen(p);
        next[1] = next[0] = 0;
        k = 0;             /* 第i 次迭代开始之前, k表示next[i-1] 的值*/     
        for (i = 2; i <= n; i++) {
            if (p[k] == p[i-1])
                k++;
            else
                k = 0;
            next[i] = k;
        }
    }
    int kmp_match(char *text, char *p, int *next)
    {
        int   m, n, s, q,num=0;
    
        m = strlen(p);
        n = strlen(text);
        q = s = 0;   /* q表示上一次迭代匹配了多少个字符,
                     s 表示这次迭代从 text的哪个字符开始比较*/
        while (s < n) {
            for (q = next[q]; q < m && p[q] == text[s]; q++, s++);
            if (q == 0) s++;
            else if (q == m) {
                num++;
                next[q] = 0;//一定要清零,不然输出个数会增加
            }
        }
        return num;
    }
  • 相关阅读:
    WPF应用程序的生命周期
    问题解决(一)在ipad上通过safari浏览文档
    C#网络编程之TCP协议(一)
    认识webMethods
    sql存储过程与webMethods
    Start to study Introduction to Algorithms
    堆和栈的区别 (转贴)
    win7平台下使用MASMPlus搭建汇编环境
    makefile
    struct类型声明的疑问
  • 原文地址:https://www.cnblogs.com/tractorman/p/4122207.html
Copyright © 2011-2022 走看看