File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed
src/pp/arithmetic/leetcode Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ package pp .arithmetic .leetcode ;
2
+
3
+ /**
4
+ * Created by wangpeng on 2019-12-27.
5
+ * 132. 分割回文串 II
6
+ *
7
+ * 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
8
+ *
9
+ * 返回符合要求的最少分割次数。
10
+ *
11
+ * 示例:
12
+ *
13
+ * 输入: "aab"
14
+ * 输出: 1
15
+ * 解释: 进行一次分割就可将 s 分割成 ["aa","b"] 这样两个回文子串。
16
+ *
17
+ * 来源:力扣(LeetCode)
18
+ * 链接:https://leetcode-cn.com/problems/palindrome-partitioning-ii
19
+ * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
20
+ */
21
+ public class _132_minCut {
22
+
23
+ public static void main (String [] args ) {
24
+ _132_minCut minCut = new _132_minCut ();
25
+ System .out .println (minCut .minCut ("aab" ));
26
+ }
27
+
28
+ /**
29
+ * 解题思路:
30
+ * 要求最少分割次数,所以在一次分割中尽可能的形成较长的回文子串,当然你也可以将所有的可能性都列出来,取其中最少的(耗时)
31
+ *
32
+ * @param s
33
+ * @return
34
+ */
35
+ public int minCut (String s ) {
36
+ boolean [][] dp = new boolean [s .length ()][s .length ()];
37
+ int [] min = new int [s .length ()];
38
+ min [0 ] = 0 ;
39
+ for (int i = 1 ; i < s .length (); i ++) {
40
+ int temp = Integer .MAX_VALUE ;
41
+ for (int j = 0 ; j <= i ; j ++) {
42
+ if (s .charAt (j ) == s .charAt (i ) && (j + 1 > i - 1 || dp [j + 1 ][i - 1 ])) {
43
+ dp [j ][i ] = true ;
44
+ if (j == 0 ) {
45
+ temp = 0 ;
46
+ } else {
47
+ temp = Math .min (temp , min [j - 1 ] + 1 );
48
+ }
49
+ }
50
+ }
51
+ min [i ] = temp ;
52
+
53
+ }
54
+ return min [s .length () - 1 ];
55
+
56
+ }
57
+ }
You can’t perform that action at this time.
0 commit comments