c++最大回文子串和最长重复子串

c++最大回文子串

暴力解法,通过循环进行遍历

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<string>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     string s;
 9     cin >> s;
10     int mx = 0;
11     int count;
12     int len = s.size();
13     for (int i = 0; i < len; i++)
14     {
15         for (int j = len - 1; j > i; j--)
16         {
17             count = 0;
18             int p = i, q = j;
19             if (s[p] != s[q])
20             {
21                  continue;
22             }
23             while (s[p] == s[q] && p < q)
24             {
25                 count++;
26                 p++;
27                 q--;
28             }
29             if (p == q) count = count * 2 + 1;
30             else if(p > q) count = 2 * count;
31             mx = max(count,mx);
32             
33         }
34     }
35     if (mx == 0) cout << 1 << endl;
36     else
37     cout << mx << endl;
38 }

c++最长重复子串,利用string库

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<string>
 4 using namespace std;
 5 
 6 
 7 //这是找最大重复子串,条件是重复2次以上的最大长度
 8 int main()
 9 {
10     string s,sub,sub_2;
11     cin >> s;
12     int mx = 0,length = 0;
13     int count =  0;
14     int len = s.size();
15     for (int i = 0; i < len - 1; i++)
16     {
17         for (int j = 1; j <= len - i; j++)
18         {    
19             count = 0;
20             sub = s.substr(i, j);
21             for (int k = 0; k <= len - sub.size(); k++)  /
22             {
23                 sub_2 = s.substr(k, sub.size());
24                 if(sub_2.find(sub) != string::npos)
25                     count++;
26             }
27             if(count >= 2)
28             {
29                 length = sub.size();
30             }
31             mx = max(mx, length);
32         }
33     }
34     cout << mx << endl;
35 }

 

原文链接: https://www.cnblogs.com/don1218/p/13154921.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    c++最大回文子串和最长重复子串

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/356301

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午11:09
下一篇 2023年3月2日 上午11:09

相关推荐