#include <stdio.h>
#include <string.h>
int ai, aj; // ai and aj to store the value of i and j respectively
int maxx(int a, int b) { // to return max of the two numbers
return (a <= b) ? b : a;
}
void LongestPal(char a[], int n) { // to find longest palindrome
int i, j, max = 0;
int p[1000][1000] = { 0 };
for (j = 0; j < n; j++)
for (i = 0; i <= j; i++) {
if (i == j) { // for one string having only one character
p[i][j] = 1;
if (max < p[i][j]) {
max = p[i][j];
ai = i;
aj = j;
}
}
if (j == (i + 1)) { // for string having two characters
if (a[i] == a[j]) { // if the string is like "aa","bb" etc.
p[i][j] = 2;
if (max < p[i][j]) {
max = p[i][j];
ai = i;
aj = j;
}
} else { // if string like "ab","ba" etc.
p[i][j] = 1;
if (max < p[i][j]) {
max = p[i][j];
ai = i;
aj = j;
}
}
} else { // for all other type of strings
if (a[i] == a[j]) { // if a longer palindrome found
p[i][j] = p[i-1][j-1] + 2;
if (max < p[i][j]) {
max = p[i][j];
ai = i;
aj = j;
}
} else { // if no longer palindrome is present
p[i][j] = maxx(p[i+1][j], p[i][j-1]);
if (max < p[i][j]) {
max = p[i][j];
ai = i;
aj = j;
}
}
}
}
}
int main() {
int i, j, n;
char a[1000];
printf("Just enter the string hoss!\n");
scanf("%s", &a);
n = strlen(a);
LongestPal(a, n);
for (i = ai; i <= aj; i++)
printf("%c", a[i]);
return 0;
}
在这个程序中,我想找到最长的回文子序列,但无法运行程序
我为每个案例写了评论
这个打印最长回文子序列的程序不起作用,当我运行它时,Windows 控制台在输入后停止工作。