poj1159 java 最长公共子序列

来源:互联网 发布:淘宝csol账号被找回 编辑:程序博客网 时间:2024/06/05 16:47
Palindrome
Time Limit: 3000MS Memory Limit: 65536KTotal Submissions: 64103 Accepted: 22347

Description

A palindrome is a symmetrical string, that is, a string read identically from left to right as well as from right to left. You are to write a program which, given a string, determines the minimal number of characters to be inserted into the string in order to obtain a palindrome.

As an example, by inserting 2 characters, the string "Ab3bd" can be transformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However, inserting fewer than 2 characters does not produce a palindrome.

Input

Your program is to read from standard input. The first line contains one integer: the length of the input string N, 3 <= N <= 5000. The second line contains one string with length N. The string is formed from uppercase letters from 'A' to 'Z', lowercase letters from 'a' to 'z' and digits from '0' to '9'. Uppercase and lowercase letters are to be considered distinct.

Output

Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.

Sample Input

5Ab3bd

Sample Output

2

题意:第一行给一个数字n,下一行由n个字符组成的字符串,求原串与自己的逆序串的最大公共子序列,再由原串长度减去刚刚求得的公共子序列长度。本题java用int类型存数组

会超内存,用short会过。

import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.Scanner;public class Main2 {@SuppressWarnings("resource")public static void main(String[] args) {         Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));         while (sc.hasNext()) {             int n=sc.nextInt();                         short dp[][]= new short[n+1][n+1];            String a=sc.next();            String b="";            for (int i = a.length()-1; i >=0; i--) {b+=a.charAt(i);}            for (int i = 0; i < dp.length; i++) {dp[i][0] = 0;}for (int i = 0; i < dp[0].length; i++) {dp[0][i] = 0;}for (int i = 1; i <= a.length(); i++) {for (int j = 1; j <= b.length(); j++) {if (a.charAt(i - 1) == b.charAt(j - 1)) {dp[i][j] = (short) (dp[i - 1][j - 1] + 1);} else {dp[i][j] = (short) Math.max(dp[i - 1][j], dp[i][j - 1]);}}}System.out.println(a.length()-dp[n][n]);}}}


阅读全文
1 0