首页 > 代码库 > Palindrome Partitioning II

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.

For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

本来是按照Palindrome Partitioning那题的思路改的,复杂度是O(n^3)吧,但是TLE了,考虑降低复杂度,算法中可以降低复杂度的只有判断字符串是否是回文那部分,因为每次计算没有考虑之前计算过的情况,将这部分提出来,用动态规划去做,isPa[i][j] = s.charAt(i) == s.charAt(j) && (i == j || i + 1 == j || isPa[i + 1][j - 1]),这样,判断回文的复杂度为O(n^2),然后自底向上计算时复杂度为O(n^2),总体的复杂度为O(n^2)。代码如下:

 1 public int minCut(String s) { 2         boolean isPa[][] = new boolean[s.length()][s.length()]; 3         if (s == null || s.equals("")) { 4             return 0; 5         } 6         for (int i = s.length() - 1; i >= 0; i--) { 7             for (int j = i; j < s.length(); j++) { 8                 isPa[i][j] = s.charAt(i) == s.charAt(j) 9                         && (i == j || i + 1 == j || isPa[i + 1][j - 1]);10             }11         }12         int result[] = new int[s.length()];13         for (int i = 0; i < s.length(); i++) {14             result[i] = 100000;15         }16         for (int i = s.length() - 1; i >= 0; i--) {17             for (int j = i; j < s.length(); j++) {18                 if (isPa[i][j]) {19                     if (j == s.length() - 1) {20                         result[i] = 0;21                     } else {22                         result[i] = result[i] < result[j + 1] + 1 ? result[i]23                                 : result[j + 1] + 1;24                     }25                 }26             }27         }28         return result[0];29     }