构成回文序列最少要增加多少字符
方法一:
为递归比较数组的头和尾:
如果头尾对应相同,则回文序列求解递归求解去头尾的回文序列(X...X => ...);
如果头尾对应不同,则有两种情况,
一种是在尾部后面添加头(X...Y => X...YX => ...Y),
一种是在头部前面添加尾(X...Y => YX...Y => X...),
解法为递归求解两种情况,取情况小的那种。
方法二:
解法二为求出字符串与逆序字符串的最长公共子串,
需要增加数目为字符串总数减去最长公共子串长度。
最长公共子串长度求解:http://blog.youkuaiyun.com/ssuchange/article/details/17341693
import java.util.Random;
public class Palindrome {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Start");
try {
test(100,10);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("End");
}
// 构成回文序列最少要增加多少字符,
// 解法一为递归比较数组的头和尾:
// 如果头尾对应相同,则回文序列求解递归求解去头尾的回文序列(X...X => ...);
// 如果头尾对应不同,则有两种情况,
// 一种是在尾部后面添加头(X...Y => X...YX => ...Y),
// 一种是在头部前面添加尾(X...Y => YX...Y => X...),
// 解法为递归求解两种情况,取情况小的那种。
public static int formPalindrome1(char[] array, int str, int end) {
if (str > end || array == null)
return 0;
if (array[str] == array[end]) {
return formPalindrome1(array, str + 1, end - 1);
}
int l1 = formPalindrome1(array, str + 1, end);
int l2 = formPalindrome1(array, str, end - 1);
return (l1 < l2 ? l1 : l2) + 1;
}
// 解法二为求出字符串与逆序字符串的最长公共子串,
// 需要增加数目为字符串总数减去最长公共子串长度。
public static int formPalindrome2(char[] array, int str, int end) {
if (str > end || array == null)
return 0;
char[] revArr = new char[array.length];
for (int i = 0; i < array.length; i++) {
revArr[array.length - 1 - i] = array[i];
}
int[][] matrix = new int[array.length][revArr.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < revArr.length; j++) {
int max = 0;
if (i - 1 >= 0 && matrix[i - 1][j] > max) {
max = matrix[i - 1][j];
}
if (j - 1 >= 0 && matrix[i][j - 1] > max) {
max = matrix[i][j - 1];
}
if (array[i] == revArr[j]) {
if (i - 1 >= 0 && j - 1 >= 0
&& matrix[i - 1][j - 1] + 1 > max)
max = matrix[i - 1][j - 1] + 1;
else if (max < 1)
max = 1;
} else {
if (i - 1 >= 0 && j - 1 >= 0 && matrix[i - 1][j - 1] > max)
max = matrix[i - 1][j - 1];
}
matrix[i][j] = max;
}
}
return array.length-matrix[array.length-1][revArr.length-1];
}
public static void test(int n,int size) throws Exception{
Random random=new Random();
char[] array;
for(int i=0;i
下载地址: