您的位置:首页 > 其它

添加最少字符使字符串整体都是回文字符串

2018-01-08 20:54 399 查看


//添加最少字符使字符串整体都是回文字符串
public class HuiString{

//动态规划法求解
//(1)获得动态规划表
public static 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;
}

//(2)根据动态规划表求出最短的回文串
public static String GetHuiString(String str)
{
if(str==null||str.length()<2)
{
return str;
}
char[]chs=str.toCharArray(); //字符串转换为数组
int[][]dp=getDp(chs); //获得动态规划数组
char[]res=new char[chs.length+dp[0][chs.length-1]]; //最终字符串数组的长度
int i=0;
int j=chs.length-1;
int resl=0;
int resr=res.length-1;
//对当前字符串的遍历
while(i<=j)
{
if(chs[i]==chs[j])
{
res[resl++]=chs[i++];
res[resr--]=chs[j--];
}else if(dp[i][j-1]<dp[i+1][j])
{
res[resl++]=chs[j];
res[resr--]=chs[j--];
}else{

res[resl++]=chs[i];
res[resr--]=chs[i++];
}

}

return String.valueOf(res);
}
//进阶问题解法
public static String getPalindrome2(String str, String strlps) {
if (str == null || str.equals("")) {
return "";
}
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 static 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)
{

String str1="ABA";
String str2="AB";
System.out.println(GetHuiString(str1));
System.out.println(GetHuiString(str2));

//进阶问题的解法
String str3="AB1CD2EFG3H43IJK2L1MN";
String strlps = "1234321";
System.out.println(getPalindrome2(str3, strlps));

}
}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐