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 are the same length, find the first one.
Retrieval string judgment algorithm:
(1) set the string to be judged 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) judge whether str [I] is equal to str [j]. If not equal, it is not a return string. If they are equal, execute I ++, j --.
(3) loop execution (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, judge 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 maxLen, Update start, stop, and maxLen, if not, continue to traverse the string to find the return string.
(4) loop execution (3) until the traversal ends.
(5) The string corresponding to start and stop is the maximum echo substring.
# Include
# Include
# Include
// Judge 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 = Len; start = I; stop = j ;}}} char * String = getStr (str, start, stop); puts (String); free (String );}