动态规划——回文串最小分割数
来源:互联网 发布:猿题库数据从何来 编辑:程序博客网 时间:2024/05/22 08:08
题目:
给定一个字符串str,返回把str全部切成回文子串的最小分割数。
举例:
str="ABA" ,不需要切割,返回0;
str="ACDCDCDAD",最少需要切两次,比如"A","CDCDC","DAD",所以返回2.
解题思路:动态规划
状态定义:
DP
[i]:表示子串(
0
,i)的最小回文切割数,则最优解在DP[s.length-
1
]中。(0,i)的子串中包括了i+1个字符,最多分割i次。
状态转移定义
:
1
.初始化:当字串str[0]--str[i]
(包括i位置的字符)是回文时,DP[i] =
0
(表示不需要分割);否则,DP[i] = i(表示至多分割i次);
2
.对于任意大于
1
的i,如果str[j]--str[i]
( 1<= j <= i ,即遍历i之前的每个子串)是回文时,DP[i] = min(DP[i], DP[j-
1
]+
1
);
(注:j不用取0是因为若j == 0,则又表示判断(0,i))。
代码:
#include <string>#include <vector>#include <iostream>#include<algorithm>using namespace std;bool IsPalindrome(const char* str, int begin, int last)//判断str[begin]--str[last]是否为回文串{int nbegin = begin;int nlast = last;while(nbegin<nlast){if (str[nbegin]!=str[nlast]) return false;nbegin++;nlast--;}return true;}int main( ){string strIn;cin>>strIn;int nlen = strIn.length();vector<int> vecDP(nlen,0);for (int i=1;i<nlen;i++){vecDP[i] = IsPalindrome(strIn.c_str(),0,i)?0:i;//初始化,若为回文串则直接为0for (int j=i;j>0;j--){if (IsPalindrome(strIn.c_str(),j,i)){vecDP[i] = min(vecDP[i],vecDP[j-1]+1);//状态转移}}}cout<<vecDP[nlen-1];//输出结果return 0;}
阅读全文
0 0
- 动态规划——回文串最小分割数
- 动态规划之回文最小分割数
- 动态规划——回文最小分割数(palindrome-partitioning-ii)
- [LeetCode]—Palindrome Partitioning II 回文分割,求最小分割数
- 回文数问题;动态规划;
- 最小回文分割数 Palindrome Partitioning II
- 【DP】回文的最小分割数
- 字符串问题---回文最小分割数
- 【DP】回文的最小分割数2
- 回文串-动态规划
- 动态规划算法之寻找最长回文数串
- 动态规划——划分为回文串
- poj1191棋盘分割—典型动态规划
- 回文数、整数输出,数字序列最小分割问题
- LeetCode-----回文串的最小分割
- 数塔—动态规划
- 回文最少分割数
- 回文最少分割数
- 使用反射以及泛型技术相结合实现简单工厂模式
- Qt5开发学习之文件及磁盘操作(十一)
- 拯救小鸡
- 477
- Spring(20)——PropertySource
- 动态规划——回文串最小分割数
- 第一天学习记录
- Django文件存储(二)定制存储系统
- OpenCV-3编译安装方法及常见错误解决(Ubuntu平台)
- 函数式编程
- iOS面试必看,最全梳理
- 实验吧-看起来有点难
- 解题报告:HDU_6184 Counting Stars (三元环计数)
- 面向对象堆栈及队列的实现