问题:
检测该字符串添加一个字符后能否成为回文串
解决:求该字符串与自身翻转形式的最长公共子序列。
(1)当最长公共子序列sublen <=len-1:
(2)其他情况不成立
code:
1 import java.util.Scanner; 2 3 public class Main21_2 { 4 public static void main(String[] args) { 5 Scanner sc = new Scanner(System.in); 6 while (sc.hasNext()) { 7 String str = sc.next(); 8 int len = str.length(); 9 int subLen = getSubstring(str); 10 if (len - subLen <= 1) 11 System.out.println("Yes"); 12 else 13 System.out.println("No"); 14 } 15 16 } 17 18 // 将字符串翻转 19 public static String reverse(String str) { 20 StringBuilder sb = new StringBuilder(str); 21 return sb.reverse().toString(); 22 } 23 24 // 求两个字符串的最长公共子序列 25 public static int getSubstring(String str) { 26 String str2 = reverse(str); 27 int i = 0; 28 int j = 0; 29 int len = str.length(); 30 int dp[][] = new int[len + 1][len + 1]; 31 for (i = 1; i <= len; i++) { 32 for (j = 1; j <= len; j++) { 33 if (str.charAt(i - 1) == str2.charAt(j - 1)) { 34 dp[i][j] = dp[i - 1][j - 1] + 1; 35 } else { 36 dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); 37 } 38 } 39 } 40 return dp[len][len]; 41 } 42 }