标签归档:回文字符串

Palindrome pku1159 回文字符串

【代码】

package pku1159;
 
/* 动态规划   状态转移方程如下:
d[i][j] = 0 (i >= j) :
d[i][j]=a[i + 1][j - 1] (ch[i] == ch[j]);
d[i][j]=min(a[i + 1)[j], a[i][j - 1]) + 1 (ch[i] != ch[j]);
*/
import java.util.*;
public class Main {
 
public static void main(String[] args) {
   Scanner cin = new Scanner(System.in);
   int n;
   n = cin.nextInt();
   String str = cin.next();
   short[][] a = new short[n + 1][n + 1];
   for (int i = n - 1; i >= 0; i--){
    for (int j = 0; j < n; j++){
     if ( i < j){
      if (str.charAt(i) == str.charAt(j))
       a[i][j] = a[i+ 1][j -1];
      else{
       a[i][j] =a[i + 1][j] < a[i][j - 1]?a[i + 1][j]:a[i][j - 1];
       a[i][j]++;
      }
 
     }
    }
   }
   System.out.println(a[0][n - 1]);
}
 
}