题目描述
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 ofs.
For example, given s ="aab",
Return1since the palindrome partitioning["aa","b"]could be produced using 1 cut.
解题思路:
- dp[]数组记录结束在任意位置的子串是否是回文 dp[i] 表示 0-i的子串是否是回文
- 对于dp[i] ,记 j 属于0到i
- 如果j到i为回文 dp[i] = Min { dp[i], dp[j] + 1}
- 如果j到i不是回文 dp[i] = Min {dp[i], dp[j] + i - j}
public class Solution {
public int minCut(String s) {
int[] dp = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
String temp = s.substring(0, i + 1);
if (isPalindrome(temp)) {
dp[i] = 0;
} else {
dp[i] = i; //初始化
}
}
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < i; j++) { // 从0-i中选择一个j 然后判断
String temp = s.substring(j + 1, i + 1);
int t;
if (isPalindrome(temp)) {
t = dp[j] + 1;
} else {
t = dp[j] + i - j + 1;
}
dp[i] = Math.min(dp[i], t);
}
}
return dp[s.length() - 1];
}
public boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}