有一个字符串S,求S最少可以被划分为多少个回文串。

例如:abbaabaa,有多种划分方式。

a|bb|aabaa - 3 个回文串

a|bb|a|aba|a - 5 个回文串

a|b|b|a|a|b|a|a - 8 个回文串

其中第1种划分方式的划分数量最少。

Input


输入字符串S(S的长度<= 5000)。

Output


输出最少的划分数量。

Input示例

abbaabaa

Output示例

3

题解


设dp[i]为考虑(i~len)的最少分割,那么

\(dp[i]=min(dp[i],dp[j+1]+1)\;if(i,j)为回文串\)

这个可以倒推也可以正推,至于求回文串

if a[i]==a[j] and (i-1,j+1)是回文串

then (i,j)是回文串,这个是\(O(n^2)\),与dp方程同级,就放在一起转移吧。

参考代码

import java.io.*;
import java.util.*; public class Main {
static final int N=(int)5005;
static int dp[]=new int[N];
static char a[]=new char[N];
static boolean p[][]=new boolean[N][N];
public static void main(String[] args) {
InputStream sys=System.in;
InputReader in=new InputReader(sys);
PrintWriter out=new PrintWriter(System.out);
a=in.next().toCharArray();
dp[a.length]=0;
for(int i=a.length-1;i>=0;i--) {
dp[i]=Integer.MAX_VALUE;
for(int j=i;j<=a.length-1;j++) {
if(a[i]==a[j]&&(j-i<2||p[i+1][j-1])) {
p[i][j]=true;
dp[i]=Math.min(dp[i], dp[j+1]+1);
}
}
}
out.println(dp[0]);
out.flush();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer; public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
} public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
} public int nextInt() {
return Integer.parseInt(next());
}
}
}

最新文章

  1. MachineKey 操作 之 获取 MachineKey
  2. linkedin开源的kafka-monitor安装文档
  3. 【转载】javascript与C#的语法区别
  4. 常见的http响应状态码
  5. unity3d - new 不出的单例
  6. Android Support Annotations :安卓注解快速上手
  7. java下载安装,环境变量,hello world
  8. Hibernate缓存机制简述 (转)
  9. 对GBK的理解(内附全部字符编码列表):扩充的2万汉字低字节的高位不等于1,而且还剩许多编码空间没有利用
  10. Eclipse+Tomcat WEB开发配置
  11. 跟我一步一步开发自己的Openfire插件
  12. 《深入剖析Tomcat》阅读(一)
  13. wcf资料
  14. 一个简单的java僵局演示示例
  15. JSP内置对象--pageContext对象(非常重要!!!)
  16. 关于如何获取iframe中的元素
  17. 在html中使用js
  18. Redis-安装、启动
  19. MonggoDB(二)
  20. 20145338 《网络对抗》逆向及Bof基础实验

热门文章

  1. 关于AFNetWorking 2.5.4之后版本编译报错问题解决方案
  2. Painful Bases LightOJ - 1021
  3. centOS 部署服务器(二)
  4. IIR型高斯滤波的原理及实现
  5. 转 多个版本的数据库在同一服务器上ORA-12557
  6. CentOS 安装图形化界面方法
  7. FFmpegUtil
  8. state vs props
  9. poj1862 Stripies
  10. viewport实现html页面动态缩放/meta viewport/viewport