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

来源:互联网 发布:wpf编程宝典c 2012 编辑:程序博客网 时间:2024/05/17 01:14

求一个字符串中连续出现次数最多的子串,例如:abcbcbcabc, 这个串中连续出出次数最多的子串是bc, 它出现了3次。

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

1 #include
2 #include
3 #include
4
5 int count = 0;
6 char sub_str[256];
7
8 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
原创粉丝点击