After a string is in reverse order and the same as the original string, the string is called a return. Given a long string, the longest return substring contained in the long string is required. If multiple input strings have the same length, find the first one.
Input string inference algorithm:
(1) set the string to be inferred to be Str. Defines two integers, I and j. I is the subscript of the first element of the string, and J is the subscript of the last element of the string.
(2) infer whether STR [I] is equal to STR [J]. If not equal, it is not a return string. If they are equal, run I ++, j --.
(3) run cyclically (2) Until I = J.
Search for the maximum input string algorithm:
(1) Use two integer variables start and stop to save the start position of the maximum input string, and use an integer variable to save the length of the maximum input string maxlen
(2) traverse from the first character of the string, infer whether the substring is a return string in turn, and find the first return string. Assign the start position to the Start and Stop variables used to record the start position in (1), and assign the length of the return to maxlen.
(3) traverse the string, find the return string, and compare the length of the return string with that of maxlen. If it is larger than that of maxlen, Update start, stop, and maxlen, if not, continue to traverse the string to find the return string.
(4) run cyclically (3) until the traversal ends.
(5) the start and stop strings are the largest response strings.
# Include <stdio. h> # include <string. h> # include <malloc. h> // infer whether the substring of the string 'str' is a return string (The position of the substring in 'str' is determined by Start and Stop) int judgehuiwen (char * STR, int start, int stop) {While (start <Stop) {If (STR [start]! = STR [Stop]) {return 0;} start ++; stop --;} return 1;} // obtain the function char * getstr (char * STR, int start, int stop) {char * string = (char *) malloc (sizeof (char) * (stop-start + 2 )); // The length of the substring is stop-start + 1, but '\ 0' must be added at the end, so the length must be set to stop-start + 2int Index = 0; for (INT I = start; I <= stop; I ++) {string [Index] = STR [I]; index ++ ;} string [Index] = '\ 0'; return string;} void main () {char STR [200]; gets (STR); int Len = strlen (STR ); int maxlen = 0; // It is used to save the maximum length of the input string int start = 0; // It is used to save the start position of the maximum input string int stop = 0; // Save the end position of the maximum echo substring for (INT I = 0; I <Len; I ++) {// search for the response substring for (Int J = I; j <Len; j ++) {If (judgehuiwen (STR, I, j )) {int Len = J-I + 1; if (LEN> maxlen) {// find the echo substring and compare it with maxlen; then maxlen = Len; Start = I; stop = J ;}}} char * string = getstr (STR, start, stop); puts (string); free (string );}