您的位置:首页 > 其它

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

2013-09-15 20:22 176 查看
求一个字符串中连续出现次数最多的子串,例如:abcbcbcabc, 这个串中连续出出次数最多的子串是bc, 它出现了3次。

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

int count = 0; 
char sub_str[256]; 

void find_str(char *str) 
9 { 
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;                         //sub string length 
19             tmp_cnt = 1; 
20             if (strncmp(&str[i], &str[j], n) == 0)   //compare n-lengths strings 
21             { 
22                 tmp_cnt++;                          //they are 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 sub string 
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 } 
50 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: