求一个字符串中连续出现次数最多的…

来源:互联网 发布:国家大数据综合试验区 编辑:程序博客网 时间:2024/05/30 19:33
本文转自:http://blog.csdn.net/huangkangying/article/details/6443302
求一个字符串中连续出现次数最多的子串,例如:abcbcbcabc,这个串中连续出出次数最多的子串是bc, 它出现了3次。

以下是我的实现代码,用c语言实现,已经编译通过。


int count= 0
char sub_str[256]; 

void find_str(char *str) 

10     int str_len= strlen(str); 
11     int i,j, k; 
12     int tmp_cnt= 0
13 
14     for (i= 0; i< str_len; i++) 
15    
16         for (j= i+1; j < str_len;j++) 
17        
18             int n=j-i;                         //substring length 
19            tmp_cnt = 1
20             if (strncmp(&str[i],&str[j], n) == 0  //comparen-lengths strings 
21            
22                tmp_cnt++;                          //theyare equal, so add count 
23                 for (k= j+n; k < str_len; k +=n)  //consecutive checking 
24                
25                     if (strncmp(&str[i],&str[k], n) == 0
26                    
27                        tmp_cnt++; 
28                    
29                     else 
30                         break
31                
32                 if (count< tmp_cnt) 
33                
34                    count = tmp_cnt; 
35                    memcpy(sub_str, &str[i],n); //record the substring 
36                
37            
38        
39 
40    
41 
42 
43 int main() 
44 
45     char *str= "abcbcbcabc"
46    find_str(str); 
47    printf("%d%s/n", count, sub_str); 
48     return 0
49 
0 0