leetcode: palindrome-partitioning-ii
阿新 • • 發佈:2019-07-29
題目描述:
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",
Return1since the palindrome partitioning["aa","b"]could be produced using 1 cut.
解題思路:
- 本題的題意是求給定字串可分割成迴文串的最小分割數
- 這題符合多階段決策模型,所以考慮用動態規劃來求解
- 設定一個 dp 陣列,依次擷取原字串的字串來判斷當前字串的分隔條件
- 設立一個單獨函式來判斷當前字串是否為迴文串
程式碼如下:
public int minCut(String s) {
int [] dp = new int[s.length()];
// 依次擷取前 i 個字元作為當前字串
for(int i = 0; i < s.length(); i++){
// 如果當前字串是迴文串,那麼它的可分割數是 0,否則先假設是最大的分割數 i
dp[i] = isHuiwen(s.substring(0,i + 1)) ? 0: i;
// 如果當前字串的可分割數為 0,那麼它是符合題意的解,故跳過
if(dp[i] == 0) continue;
// 如果當前字串的可分割數不是 0,則需要依次擷取當前字串的子字串判斷
for(int j = 1; j <= i; j++){
// 如果當前字串是迴文串,那麼它的可分割數就需要重新給定
if(isHuiwen(s.substring(j,i + 1)))
// 狀態轉移方程
dp[i] = Math.min(dp[i],dp[j - 1] + 1);
// 如果不是迴文串,就需要重新給定值
else
dp[i] = Math.min(dp[i],dp[j - 1] + i + 1 - j);
}
}
return dp[dp.length - 1];
}
// 判斷當前字串是否為迴文串
private boolean isHuiwen(String s){
boolean flag = true;
int i = 0;
int j = s.length() - 1;
while(i < j){
if(s.charAt(i) != s.charAt(j)){
flag = false;
break;
}
i++;
j--;
}
return