/**
* Created by lxw, liwei4939@126.com on 2017/10/31.
* 添加最少的字符使整体字符串都是回文字符串
*
* 1.给定字符串str,可以在str的任意位置添加字符,返回在
* 添加字符最少的情况下,让str整体都是回文字符串的一种结果
* 代码 getPalindrome1
*
* 2.给定字符串str和str的最长回文子序列字符串strlps,返回在
* 添加字符最少的情况下,让str整体都是回文字符串的一种结果
* 代码 getPalindrome2
*/
public class palindrome {
public int[][] getDP(char[] str){
int[][] dp = new int[str.length][str.length];
for (int j = 1; j< str.length; j++){
dp[j-1][j] = str[j-1] == str[j] ? 0 : 1;
for (int i = j-2; i> -1; i--){
if(str[i] == str[j]){
dp[i][j] = dp[i+1][j-1];
} else {
dp[i][j] = Math.min(dp[i+1][j], dp[i][j-1]) + 1;
}
}
}
return dp;
}
public String getPalindrome1(String str){
if(str == null || str.length() < 2){
return str;
}
char[] arrStr = str.toCharArray();
int[][] dp = getDP(arrStr);
char[] res = new char[arrStr.length + dp[0][arrStr.length - 1]];
int i = 0;
int j = arrStr.length - 1;
int resl = 0;
int resr = res.length - 1;
while (i <= j){
if(arrStr[i] == arrStr[j]){
res[resl++] = arrStr[i++];
res[resr--] = arrStr[j--];
} else if(dp[i][j-1] < dp[i+1][j]){
res[resl++] = arrStr[j];
res[resr--] = arrStr[j--];
} else {
res[resl++] = arrStr[i];
res[resr--] = arrStr[i++];
}
}
return String.valueOf(res);
}
public String getPalindrome2(String str, String strlps){
if(str == null || str.equals("")){
return str;
}
char[] chas = str.toCharArray();
char[] lps = strlps.toCharArray();
char[] res = new char[2*chas.length - lps.length];
int chasl = 0;
int chasr = chas.length - 1;
int lpsl = 0;
int lpsr = lps.length - 1;
int resl = 0;
int resr = res.length - 1;
int tmpl = 0;
int tmpr = 0;
while (lpsl <= lpsr){
tmpl = chasl;
tmpr = chasr;
while (chas[chasl] != lps[lpsl]){
chasl++;
}
while (chas[chasr] != lps[lpsr]){
chasr--;
}
set(res, resl, resr, chas, tmpl, chasl, chasr, tmpr);
resl += chasl - tmpl + tmpr - chasr;
resr -= chasl - tmpl + tmpr - chasr;
res[resl++] = chas[chasl++];
res[resr--] = chas[chasr--];
lpsl++;
lpsr--;
}
return String.valueOf(res);
}
public void set(char[] res, int resl, int resr, char[] chas,
int ls, int le, int rs, int re){
for (int i = ls; i< le; i++){
res[resl++] = chas[i];
res[resr--] = chas[i];
}
for (int i = re; i>rs; i--){
res[resl++] = chas[i];
res[resr--] = chas[i];
}
}
public static void main(String[] args){
palindrome tmp = new palindrome();
String str1 = "AB";
System.out.println(tmp.getPalindrome1(str1));
String str2 = "A1B21C";
String strlps = "121";
System.out.println(tmp.getPalindrome2(str2, strlps));
}
}
添加最少的字符使整体字符串都是回文字符串
最新推荐文章于 2024-07-17 10:35:12 发布