Topics
Enter a line of string to find the same and longest string that appears, outputting it and the position of the first character.
Input
yyabcdabjcabceg
Output
abc3
parsing
First declare that if the string is aaaaaa, the answer should be aaaaa. Two equal-length substrings can have some overlapping characters.
Take Abcab as an example to analyze the following:
First look for substrings of length 4, only ABCA and Bcab, and then see if the two substrings have other identical substrings. Some words directly output the result and exit the program.
Then look for a substring of length 3, only abc,bca,cab. None of the 3 substrings have the same substring.
Finally, a substring of length 2 is searched, AB First, and the Find function returns the position 0 in the Abcab, with the RFind function returning the position 3 in reverse order found in Abcab. These two positions are not equal, indicating that the same substring AB exists in different locations.
Code
#include <iostream>Using namespace std;pair<int,string> Fun (const string &Str){int Count=0; String Substrs, Tep;intI, j, len =Str. Length (); for(i = len-1; I >=1; -I.) { for(j =0; J <= Len-i; J + +) {size_t T =0; size_t num =0; TEP =Str. substr (J,i); t =Str. find (TEP); num =Str. RFind (TEP);if(t! = num) {Count= T +1; Substrs = Tep;returnMake_pair (Count, substrs); } } }returnMake_pair (Count, substrs);}intMain () {stringStr; pair<int,string> rs; CIN >>Str; rs = Fun (Str); cout << rs.second << endl << rs.first << Endl;return 0;}
Geek programming Exercises-the longest same substring