问题:给定一个字符串,问是否能通过添加一个字母将其变为回文串。
思路:
<span style="color:#FF0000;"> </span><p><span style="font-family:arial,STHeiti,Microsoft YaHei,宋体;font-size:12px;color:#FF0000;"><span style="line-height:19.11931800842285px">在做测试时有三种情况:</span></span></p><p><span style="font-family:arial,STHeiti,Microsoft YaHei,宋体;font-size:12px;color:#FF0000;"><span style="line-height:19.11931800842285px">(1)aba型,本来就是回文串</span></span></p><p><span style="font-family:arial,STHeiti,Microsoft YaHei,宋体;font-size:12px;color:#FF0000;"><span style="line-height:19.11931800842285px">(2)abac型,在串的左边或右边添加另一侧的字符,变成回文串</span></span></p><p><span style="font-family:arial,STHeiti,Microsoft YaHei,宋体;font-size:12px;color:#FF0000;"><span style="line-height:19.11931800842285px">(3)abceba型,在串的中间添加字符,形成回文串。</span></span></p><p><span style="font-family:arial,STHeiti,Microsoft YaHei,宋体;font-size:12px;color:#FF0000;"><span style="line-height:19.11931800842285px">然而普通做法,前两种很好判断和处理,只有第三种比较麻烦。</span></span></p><p><span style="font-family:arial,STHeiti,Microsoft YaHei,宋体;font-size:12px;color:#FF0000;"><span style="line-height:19.11931800842285px">那么解决的方法就是动态规划,利用源字符串和翻转后的字符串,求最长公共子序列。长度-公共子序列的长度=添加字符的个数。</span></span></p>
/**
*判断原字符串和翻转字符串的最长公共子序列长度是否比原字符串长度小1或相等
*/
importjava.util.*;
public class Main
{
public static int lcs(String s, String s1)
{
if(s == null|| s1 == null) {
return0;
}
intm = s.length();
intn = s1.length();
int[][] dp = new int[m + 1][n + 1];
dp[0][0] = 0;
for(inti = 1; i < m; i++) {
dp[0][i] = 0;
}
for(inti = 1; i < m; i++) {
dp[i][0] = 0;
}
for(inti = 1;i < m + 1; i++) {
for(intj = 1; j < n + 1; j++) {
if(s.charAt(i - 1) == s1.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else{
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()) {
String s= scanner.nextLine();
String s1 = new StringBuilder(s).reverse().toString();
int len = lcs(s, s1);
if(s.length() - len <= 1) {
System.out.println("YES");
} else{
System.out.println("NO");
}
}
}
}