回文字符串

    xiaoxiao2021-03-26  21

    回文字符串

    时间限制: 3000 ms  |  内存限制: 65535 KB 难度: 4 描述 所谓回文字符串,就是一个字符串,从左到右读和从右到左读是完全一样的,比如"aba"。当然,我们给你的问题不会再简单到判断一个字符串是不是回文字符串。现在要求你,给你一个字符串,可在任意位置添加字符,最少再添加几个字符,可以使这个字符串成为回文字符串。 输入 第一行给出整数N(0<N<100) 接下来的N行,每行一个字符串,每个字符串长度不超过1000. 输出 每行输出所需添加的最少字符数 样例输入 1 Ab3bd 样例输出 2

    import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); int n=scanner.nextInt(); while(n--!=0) { String str1=scanner.next(); String str2=new StringBuffer(str1).reverse().toString(); char arr1[]=str1.toCharArray(); char arr2[]=str2.toCharArray(); int len1=arr1.length; int temp[][]=new int[len1+2][len1+2]; for(int i=1;i<=len1;i++) { for(int j=1;j<=len1;j++) { if(arr1[i-1]==arr2[j-1]) { temp[i][j]=temp[i-1][j-1]+1; } else { temp[i][j]=temp[i-1][j]>temp[i][j-1]?temp[i-1][j]:temp[i][j-1]; } } } System.out.println(len1-temp[len1][len1]); } } }

    转载请注明原文地址: https://ju.6miu.com/read-660525.html

    最新回复(0)