转载请注明来自souldak,微博:@evagle

上一篇是要输出所有的可能拆分,这回是要输出拆分次数最少的切割次数。

如果直接按照上一篇那么做的话,就会超时,因为我们在判断s[i][j]是否是回文的时候做了很多的无用功,每一个s[i][j]都用字符串计算了一遍,然而实际上可以根据s[i+1][j+1]推算出来的。

题目。代码如下

/**
* @file Palindrome_Partitioning2.cpp
* @Brief
* @author Brian
* @version 1.0
* @date 2013-09-06
*/ #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory.h>
#include <algorithm>
#include <math.h>
#include <queue>
#include <vector>
using namespace std;
#define MAXINT 0x7fffffff class Solution {
public:
int minCut(string s) { int len = s.length();
int* cutNum = new int[len];
//int[i][j]: true if substr(i,j) is palindrome, false if not
bool** palindrome = new bool*[len];
for(int i=0;i<len;i++)
palindrome[i] = new bool[len];
//init palindrome for(int l=0;l<=len;l++){
for(int i=0;i<=len-l&&i<len;i++){
if(l==1||l==0) palindrome[i][l] = true;
else{
palindrome[i][l] = palindrome[i+1][l-2]&&(s[i]==s[i+l-1]);
}
}
}
for(int i=0;i<len;i++)
cutNum[i]=MAXINT;
cutNum[0]=0;
for(int i=1;i<len;i++){
for(int j=0;j<=i;j++){
string subs = s.substr(j,i-j+1);
if(palindrome[j][i-j+1]){
if(j==0){
cutNum[i]=0;
}else{
if(cutNum[i]>cutNum[j-1]+1)
cutNum[i] = cutNum[j-1]+1;
}
} }
}
return cutNum[len-1];
}
bool is_palindrome(string s){
if(s.length() <= 1)
return true;
else{
for(int i=0;i<s.length()/2;i++){
if(s[i]!=s[s.length()-i-1]){
return false;
}
}
}
return true; }
};
int main(){
Solution s;
cout<< s.minCut("abv"); return 0;
}

最新文章

  1. 【Spring】搭建最简单的Spring MVC项目
  2. 【leetcode❤python】70. Climbing Stairs
  3. Cryptography - JavaScript 加密算法库
  4. BZOJ 1004 Cards(Burnside引理+DP)
  5. pip error: command &#39;gcc&#39; failed with exit status 1
  6. motan源码分析二:使用spi机制进行类加载
  7. Example_07_05录音提示open failed: EACCES (Permission denied)
  8. Source insight添加工具自动排版
  9. session.createQuery()不执行和java.lang.reflect.InvocationTargetException
  10. 经常使用Javascript CDN 对照
  11. web项目中图标的前端处理方案
  12. buils tool是什么?为什么使用build tool?java主流的build tool
  13. Centos6安装和配置etcd3
  14. 【XSY2669】归并排序 树状数组 简单组合数学
  15. mybatis入门--单表的增删改操作
  16. Hadoop副本数配置
  17. 文件上传:input file FileReader
  18. Delphi.format填充0
  19. ssh连接失败, 记下来原因和解决方案
  20. Scala实战高手****第17课:Scala并发编程实战及Spark源码阅读

热门文章

  1. WM_PAINT在微软官方定义中,wParam和lParam都没有使用,所以就被Delphi给重定义了这个消息,还增加了DC(Delphi可任意改写消息的结构)
  2. [置顶] RFS的web自动化验收测试——常见问题指引
  3. 如何使用NArrange进行代码优化
  4. EasyUI - According 分类列表
  5. QSettings操作配置文件
  6. HDU3709:Balanced Number(数位DP+记忆化DFS)
  7. (原创)优酷androidclient 下载中 bug 解决
  8. 杭电 1711 Number Sequence
  9. ios-王云鹤 调用ios系统功能---------------打电话、发短信、发邮件
  10. mysql 执行计划走索引