加入任意数量的任意字符,使其字符串变成回文串
思路:
先反转输入的字符串,然后遍历,与原字符串比较,找到reverse对应s的前缀
例如 s:noo reverse:oon
当i=0时,不匹配
当i=1时,匹配
所以需要在s后加入n,index为reverse.length()-i
public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); String reverse = new StringBuffer(s).reverse().toString(); String ans = ""; int len = Integer.MAX_VALUE; if (judge(s)) { System.out.println(s); } else { for (int i = 0; i < reverse.length(); i++) { //判断reverse中的字符串是否与s从第i个位置开始的子字符串相等。 if (reverse.startsWith(s.substring(i))) { String tmp = s + reverse.substring(reverse.length() - i); if (tmp.length() < len) { len = tmp.length(); ans = tmp; } // 为什么不直接输出呢?因为可能会有多个输出,我要输出最短的那个 // System.out.println(s+reverse.substring(reverse.length()-i)); } } System.out.println(ans); } } public static boolean judge(String s) { int left = 0, right = s.length() - 1; while (left <= right) { if (s.charAt(left) == s.charAt(right)) { left++; right--; } else { return false; } } return true; } }
分类:
题解分享