The 15-2 (longest sub-string) palindrome is a non-empty string with the same forward and backward orders. For example, all strings with a length of 1, civic, racecar, and aibohphobia are input files. Design an efficient algorithm to obtain the longest echo sub-sequence of a given input string. For example, given the input character, what is the running time of the carac algorithm?
Solutions: First, we should note that the question requirements should be obtained.Longest echo subsequenceInsteadSubstring. If it is a substring, such as abcdebca, the length of the substring is 1, which is any one of the characters, and the substring is abcdbca (abcebca ). therefore, there are some differences between substrings and subsequences. The following method applies only to subsequences. The substring method is not required because the question is not required. (PS: some people may not know the difference between substrings and subsequences. This is a special issue .)
Method: You only need to reverse the original string and compare it with the original string and use the longest common subsequence to obtain the longest echo subsequence. That is to say, the obtained LCS = the longest echo subsequence.
The Code is as follows::
# Include <iostream> using namespace STD; # define N 9 // enter the number of characters in the string to be judged. char * strreversal (char * Str) {for (INT I = 0; I <n/2; I ++) {swap (STR [I], STR [N-i-1]);} return STR ;} char * B [n + 2] [n + 2] = {null}; int C [n + 2] [n + 2] = {0 }; void lcs_length (char * X, char * Y) {for (INT I = 0; I <n; I ++) {for (Int J = 0; j <N; j ++) {If (X [I] = Y [J]) {c [I + 1] [J + 1] = C [I] [J] + 1; B [I + 1] [J + 1] = "";} else {If (C [I] [J + 1]> = C [I + 1] [J]) {c [I + 1] [J + 1] = C [I] [J + 1]; B [I + 1] [J + 1] = "yellow" ;} Else {C [I + 1] [J + 1] = C [I + 1] [J]; B [I + 1] [J + 1] = "char" ;}}} void print_lcs (char * X, int I, Int J) {if (I = 0 | j = 0) {return;} If (B [I] [J] = "") {print_lcs (x, I-1, j-1); cout <X [I-1] <";} else {If (B [I] [J] =" inline ") {print_lcs (x, I-1, j);} else {print_lcs (X, I, J-1) ;}} void main () {// to match the code in the book, empty characters are stored in the first position of the array. Char X [n + 1] = {0}; char y [n + 1] = {0}; char C; cout <"Tip: before entering a string, set the n size as needed "<Endl; cout <" Enter the string to be judged: "<Endl; For (INT I = 0; I <N; I ++) {CIN> C; y [I] = x [I] = C;} y [I] = '\ 0 '; X [I] = '\ 0'; strreversal (y); // reverse the string cout <"x =" <x <Endl; cout <"Y =" <Y <Endl; lcs_length (x, y); print_lcs (x, n, n );}
Sample output:
Conclusion: It takes O (n2) Time to evaluate LCs and O (n) Time to reverse the string. In general, this program only requires O (n2) time. This problem is still relatively simple. You only need to change the examples in the book to get the expected results.
Zookeeper