zoukankan      html  css  js  c++  java
  • 找出字符串中连续出现次数最多的子串

    /*
    基本算法描述:
    给出一个字符串abababa
    1.穷举出所有的后缀子串
    substrs[0] = abababa;
    substrs[1] = bababa;
    substrs[2] = ababa;
    substrs[3] = baba;
    substrs[4] = aba;
    substrs[5] = ba;
    substrs[6] = a;
    2.然后进行比较
    substrs[0]比substrs[1]多了一个字母,如果说存在连续匹配的字符,那么
    substrs[0]的第1个字母要跟substrs[1]首字母匹配,同理
    substrs[0]的前2个字母要跟substrs[2]的前2个字母匹配(否则不能叫连续匹配)
    substrs[0]的前n个字母要跟substrs[n]的前n个字母匹配.
    如果匹配的并记下匹配次数.如此可以求得最长连续匹配子串.
    */

    int count = 0; 
    char sub_str[256]; 
    
    void find_str(char *str) 
    { 
         int str_len = strlen(str); 
         int i, j, k; 
         int tmp_cnt = 0; 
     
         for (i = 0; i < str_len; i++) 
         { 
             for (j = i+1; j < str_len; j++) 
             { 
                 int n = j-i;                         //sub string length 
                 tmp_cnt = 1; 
                 if (strncmp(&str[i], &str[j], n) == 0)   //compare n-lengths strings 
                 { 
                     tmp_cnt++;                          //they are equal, so add count 
                     for (k = j+n; k < str_len; k += n)  //consecutive checking 
                     { 
                         if (strncmp(&str[i], &str[k], n) == 0) 
                         { 
                             tmp_cnt++; 
                         } 
                         else 
                             break; 
                     } 
                     if (count < tmp_cnt) 
                     { 
                         count = tmp_cnt; 
                         memcpy(sub_str, &str[i], n); //record the sub string 
                     } 
                 } 
             } 
     
         } 
     } 
  • 相关阅读:
    ASP.NET对IIS中的虚拟目录进行操作
    QLive EULA
    Windows Phone在模拟器中去除Debug信息
    Windows Phone区别应用是App还是Game
    UI Automation By Microsoft
    UIA: Choose item in Combobox
    身份证号码验证 C#
    Windows Phone 获取窗口大小
    重载 Sort, ==, !=
    C++枚举类型
  • 原文地址:https://www.cnblogs.com/freewater/p/2676001.html
Copyright © 2011-2022 走看看