添加最少字符使字符串整体都是回文字符串
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));
}
}
相关文章推荐
- 添加最少的字符使整体字符串都是回文字符串
- 牛客面试算法题精讲【个人总结】- 添加最少字符以使字符串整体都是回文字符串
- 字符串问题---添加最少字符使字符串整体都是回文字符串
- 一个字符串要变成回文串的需要添加的字符最少个数
- 算法:动态规划——区间模型之最少添加几个字符使得字符串变成回文串
- hdu 3746 Cyclic Nacklace(求最少添加几个字符使得字符串是由n(n>=2)个循环节组成的)
- 添加最少字符使成为回文字符串
- HDU 3746 将字符串的全部字符最少循环2次需要添加的字符数
- 每日AC- 美团 -- 直方图中最大矩形 与最少字符使字符串变成回文字符串
- CSDN上一篇帖子:用最少的代码从一个字符串中找到出现频率最高的字符
- [每天一题]判断字符串里否是都是独一无二的字符(不要用额外空间)
- 插入最少的字符使字符串成为回文串
- C++输入一个字符串,去掉这个字符串中出现次数最少的字符 例如: 输入:abcabbc 输出:bbb
- 插入最少的字符使字符串成为回文
- STL学习-字符串回文判断以及实现删除字符串中重复字符最少字符
- uva 11584 题目大意: 给一个字符串, 要求把它分割成若干个子串,使得每个子串都是回文串。问最少可以分割成多少个。
- (字符串的处理4.7.13)POJ 2141 Message Decowding(字符串的加密与解密&&所有都是字符且是2行形式的输入输出处理)
- 插入最少的字符使字符串成为回文串 <最长公共子序列 + 回文>
- 删除字符串中出现次数最少的字符