动态规划——回文最小分割数(palindrome-partitioning-ii)
2016-07-17 21:06
253 查看
题目:
给定一个字符串str,返回把str全部切成回文子串的最小分割数。
举例:
str="ABA" ,不需要切割,返回0;
str="ACDCDCDAD",最少需要切两次,比如"A","CDCDC","DAD",所以返回2.
给定一个字符串str,返回把str全部切成回文子串的最小分割数。
举例:
str="ABA" ,不需要切割,返回0;
str="ACDCDCDAD",最少需要切两次,比如"A","CDCDC","DAD",所以返回2.
public class Solution { public int minCut(String s) { if(s == null||s.length() == 0) return 0; int[] dp=new int[s.length()]; //dp[i]存放(0,i)即以i的字符结束的子串的最小切割数,则所求为dp[s.length()-1]; dp[0]=0;//一个字符,不需要切割 for(int i=1;i<s.length();i++) { //dp[i]赋初值 dp[i]=is_palindrome(s.substring(0,i+1))?0:i+1; // 1=<j<=i的子串回文判定 for(int j=i;j>=1;j--) { if(is_palindrome(s.substring(j,i+1))) { dp[i]=Math.min(dp[i],dp[j-1]+1); } } } return dp[s.length()-1]; } //判断回文串例程 public boolean is_palindrome(String s) { int begin=0; int end=s.length()-1; while(begin<end) { if(s.charAt(begin)!=s.charAt(end)) return false; begin++; end--; } return true; } }
相关文章推荐
- 21.Which three statements are true about logical structures of the Oracle database? (Choose three.)
- Xcode中pch文件的使用
- WebServer 之apache(httpd2.2和httpd2.4)基础安装部署
- .NET中制做对象的副本(二)继承对象之间的数据拷贝
- Delphi编程中Http协议应用
- 7.17 leetcode 第一天刷题成功
- Java Se----语言基础(1)
- 乘风破浪会有时,直挂云帆济沧海。
- App的打磨之路(中)
- 随笔
- 【NYOJ】[833]取石子(七)
- 安卓项目之淘忆2.0的界面设计部分一
- LeetCode - 89. Gray Code
- Recycler的一些笔记
- 使用WebDriver 登录163邮箱
- 线程的状态
- python学习-模块
- 报时助手
- Windows10 64位 Python2.7 Matplotlib安装
- 线程的状态