LeetCode 132. Palindrome Partitioning II
132. Palindrome Partitioning II
Description Submission Solutions
- Total Accepted: 65178
- Total Submissions: 276173
- Difficulty: Hard
- Contributors: Admin
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.
Subscribe to see which companies asked this question.
【题目分析】
给定一个字符串,把该字符串切成几段,每段都是一个回文字符串,那么最少的切割次数是多少次?
【思路】
1. 递归
a. 如果当前字符串是回文串,则返回0;
b. 否则找到以第一个字符串开头的回文字符串,该子字符串使得剩下的字符串的切割数最少。
2. 动态规划
先把代码贴下面,但是还没有理解 discuss
【java代码——递归】该算法会导致超时
1 public class Solution { 2 public int minCut(String s) { 3 if(isPalindrome(s)) return 0; 4 int res = s.length()-1; 5 6 for(int i = 1; i < s.length(); i++) { 7 if(!isPalindrome(s.substring(0,i))) continue; 8 res = Math.min(res, minCut(s.substring(i))+1); 9 } 10 11 return res; 12 } 13 14 public boolean isPalindrome(String s) { 15 if(s.length() <= 1) return true; 16 int left = 0, right = s.length()-1; 17 while(left < right) { 18 if(s.charAt(left++) != s.charAt(right--)) return false; 19 } 20 21 return true; 22 } 23 }
【c++代码2——动态规划】
1 class Solution { 2 public: 3 int minCut(string s) { 4 int n = s.size(); 5 vector<int> cut(n+1, 0); // number of cuts for the first k characters 6 for (int i = 0; i <= n; i++) cut[i] = i-1; 7 for (int i = 0; i < n; i++) { 8 for (int j = 0; i-j >= 0 && i+j < n && s[i-j]==s[i+j] ; j++) // odd length palindrome 9 cut[i+j+1] = min(cut[i+j+1],1+cut[i-j]); 10 11 for (int j = 1; i-j+1 >= 0 && i+j < n && s[i-j+1] == s[i+j]; j++) // even length palindrome 12 cut[i+j+1] = min(cut[i+j+1],1+cut[i-j+1]); 13 } 14 return cut[n]; 15 } 16 };