输出包含两行,第一行包含一个字符串代表str,第二行包含一个字符串,代表strips。
输出一行,代表返回的值。
A1B21C 121
AC1B2B1CA
str=“A1B21C",strlps="121",返回“AC1B2B1CA”或者“CA1B2B1AC”,总之,只要是添加的字符数最少,只返回其中一种结果即可。
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class Main { private static String getPalindrome(String str, String strlps) { if (str == null || str.equals("")) { return ""; } char[] chas = str.toCharArray(); char[] lps = strlps.toCharArray(); int strLen = chas.length; int lpsLen = lps.length; int resLen = 2 * strLen - lpsLen; char[] res = new char[resLen]; int chasl = 0; int chasr = strLen - 1; int lpsIdx = 0; int resIdx = 0; while (chasl <= chasr) { if (chas[chasl] != lps[lpsIdx]) { res[resIdx] = chas[chasl]; res[resLen - resIdx - 1] = chas[chasl++]; } else if (chas[chasr] != lps[lpsIdx]) { res[resIdx] = chas[chasr]; res[resLen - resIdx - 1] = chas[chasr--]; } else { res[resIdx] = lps[lpsIdx]; res[resLen - resIdx - 1] = lps[lpsIdx]; chasl++; chasr--; lpsIdx++; } resIdx++; } return new String(res); } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); String strlps = br.readLine(); System.out.println(getPalindrome(str, strlps)); } }