Find all the longest continuous repeated substrings and their numbers, and the longest number
Problem description:
Returns the maximum number of consecutive repeated substrings in a string.
For example:
Input: 123234. the maximum number of consecutive repeated strings is 23 and the number is 2.
Input: 5555. the maximum number of consecutive repeated strings is 555 and the number is 2.
Input: the maximum number of consecutive repeated aaabbb strings is aa, the number is 2, and bb, the number is 2
A duplicate string is required. There may be multiple different strings of the same length, such as aaabbb.
Solutions
The difference from [finding the substrings with the most consecutive occurrences in a string] is reflected in two aspects: first, finding the longest substring (repeated times greater than or equal to 2 ); second, we need to consider that the substrings are overlapped. For example, the longest substring of eeee is eee. In the previous question, overlap is certainly not the most frequent occurrence.
Implementation Code
# Include <iostream> # include <cstring> # include <utility> # include <string> # include <vector> using namespace std; vector <pair <int, string> fun (const string & str) {vector <string> subs; vector <pair <int, string> res; int len = str. size (); for (int I = 0; I <len; I ++) {subs. push_back (str. substr (I);} int count = 1; int maxCount = 1; int subLen = 1; string sub; // I is the length of the substring for (int I = 1; I <len; I ++ ){ For (int j = 0; j <len-1; j ++) {count = 1; for (int k = j + 1; k <= j + I & subs [k]. size ()> = I; k ++) {if (subs [k]. substr (0, I) = subs [j]. substr (0, I) {count ++; break ;}} if (count> = 2) {if (I> subLen) {res. clear () ;}sublen = I; maxCount = count; sub = subs [j]. substr (0, I); res. push_back (make_pair (maxCount, sub) ;}} return res ;}int main () {string str; vector <pair <int, string> r Es; while (cin> str) {res = fun (str); for (auto it = res. begin (); it! = Res. end (); it ++) {cout <it-> second <":" <it-> first <endl ;}} return 0 ;}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.