博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode刷题:132. Palindrome Partitioning II (JAVA算法实现)
阅读量:4039 次
发布时间:2019-05-24

本文共 1257 字,大约阅读时间需要 4 分钟。

LeetCode刷题:132. Palindrome Partitioning II

原题链接:

Given a string s, partition s such that every substring of the partition is a palindrome.

Return the minimum cuts needed for a palindrome partitioning of s.

Example:

Input: "aab"

Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.

给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。

返回符合要求的最少分割次数。

示例:

输入: "aab"

输出: 1
解释: 进行一次分割就可将 s 分割成 ["aa","b"] 这样两个回文子串。


算法设计

/*	 * 基本思想是使用两个DP数组:	 * 使用isPalindrome[i,j]来记录 s[i, j]是否为回文串,	 * 以及num[i]来记录对于s[0,i]的最小划分。	 * 这里s[i,j]代表的含义是:s.substring(i,j+1)。	 * 遍历访问数组以计算:num 和 ispalindrome。	 * num[s.length()-1]是我们想要的结果。	 * 注意,如果s[0,i]是回文串,那么num[i]等于零,因为我们不需要划分它来得到回文序列。	 * */		public int minCut(String s) {	    char str[] = s.toCharArray();	    boolean isPalindrome[][] = new boolean[s.length()][s.length()];	    int num[] = new int[s.length()];	    for(int i = 0; i < s.length(); i++) {	        int min = Integer.MAX_VALUE;	        for(int j = 0; j <= i; j++) {	            if( str[i] == str[j] && (j + 1 >= i || isPalindrome[j + 1][i - 1]) ){	                isPalindrome[j][i] = true;	                min = j == 0 ? 0 : Math.min(min, num[j - 1] + 1);	            }	        }	        num[i] = min;	    }	    return num[s.length() - 1];	}

Accepted~

转载地址:http://wntdi.baihongyu.com/

你可能感兴趣的文章
【leetcode】Sum Root to leaf Numbers
查看>>
【leetcode】Pascal's Triangle II (python)
查看>>
java自定义容器排序的两种方法
查看>>
如何成为编程高手
查看>>
本科生的编程水平到底有多高
查看>>
AngularJS2中最基本的文件说明
查看>>
从头开始学习jsp(2)——jsp的基本语法
查看>>
使用与或运算完成两个整数的相加
查看>>
备忘:java中的递归
查看>>
DIV/CSS:一个贴在左上角的标签
查看>>
/proc文件系统读出来的数据是最新的吗?
查看>>
Solr及Spring-Data-Solr入门学习
查看>>
Vue组件
查看>>
python_time模块
查看>>
python_configparser(解析ini)
查看>>
selenium学习资料
查看>>
<转>文档视图指针互获
查看>>
Matlab subplot 图像间距调整
查看>>
从mysql中 导出/导入表及数据
查看>>
HQL语句大全(转)
查看>>