腾讯暑假实习面试题
题目:给定一个字符串s,你可以从中删除一些字符,使得剩下的串是一个回文串。如何删除才能使得回文串最长呢?
输出需要删除的字符个数。
思路:该题目可以先将字符串s倒序然后求倒序字符串与原来字符串的最长公共子序列(动态规划:dp[i][j] 表示的是Str1[0...i] 与 Str2[0...j] 的最长公共子序列的长度),其余的就是需要删除的字符串
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = "google";
//in.nextLine();
char[] reverseArray = reverse(str);
char[] strArray = str.toCharArray();
int len = comChar(strArray, reverseArray);
System.out.println(len);
System.out.println(str.length() - len);
}
public static char[] reverse(String str) {
int left = 0;
int right = str.length() - 1;
char[] array = str.toCharArray();
while (left < right) {
array[left] = (char) (array[left] ^ array[right]);
array[right] = (char) (array[right] ^ array[left]);
array[left] = (char) (array[left] ^ array[right]);
left++;
right--;
}
return array;
}
public static int comChar(char[] arr, char[] arr2) {
int[][] dp = new int[arr.length][arr2.length];
int len = arr.length;
dp[0][0] = arr[0] == arr2[0] ? 1 : 0;
for (int i = 1; i < len; i++) {
dp[0][i] = Math.max(dp[0][i - 1], arr[0] == arr2[i] ? 1 : 0);
dp[i][0] = Math.max(dp[i - 1][0], arr2[0] == arr[i] ? 1 : 0);
}
for (int i = 1; i < len; i++) {
for (int j = 1; j < len; j++) {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
if (arr[i] == arr2[j]) {
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - 1] + 1);
System.out.println(i + " " + j + ":" + dp[i][j]);
}
}
}
return dp[len - 1][len - 1];
}
}