题目描述
给定一个字符串,问是否能通过添加一个字母将其变为回文串。
输入描述:
一行一个由小写字母构成的字符串,字符串长度小于等于10。
输出描述:
输出答案(YES\NO).
输入例子:
coco
输出例子:
YES
思路通过将字符串反转后,与原字符串进行最长公共子串处理,得到lcs的值,则所需添加长度 = 字符串长度-lcs,判断是否小于等于1即可public class Solution { public static void main(String[] args) { // TODO 自动生成的方法存根 String s = "coco"; System.out.println(Solution.canBeHUIWEN(s) ); } public static String canBeHUIWEN(String s) { String reverseS = reverse(s.toCharArray()); int lcs = LCS(s, reverseS); int addNums = s.length() - lcs; if (addNums <= 1) return "yes"; else return "no"; } public static String reverse(char[] str) { int s = 0; int e = str.length - 1; while (s < e) { char temp = str[s]; str[s] = str[e]; str[e] = temp; ++s; --e; } return new String(str); } public static int LCS(String s1, String s2) { int len1 = s1.length(); int len2 = s2.length(); String res = ""; int[][] DP = new int[len1 + 1][len2 + 1];// 初始化一个比两个字符串长度+1的二维数组 for (int i = 0; i <= len1; i++) { for (int j = 0; j <= len2; j++) { if (i == 0 || j == 0) { DP[i][j] = 0;// 从边界开始,当一个字符串为空的时候,肯定为0 } // 如果xm=yn,则zk=xm=yn 有Zk−1是Xm−1与Yn−1的LCS; else if (s1.charAt(i - 1) == s2.charAt(j - 1)) { DP[i][j] = 1 + DP[i - 1][j - 1]; } else { // 如果xm≠yn,则Zk是Xm与Yn−1的LCS,或者是Xm−1与Yn的LCS。 DP[i][j] = Math.max(DP[i - 1][j], DP[i][j - 1]); } } } // System.out.println(res); return DP[len1][len2]; // return res; } }