Sponsored
Sponsored
This approach involves using two DP tables. One to check if a substring is a palindrome and another to compute the minimum cuts required.
We maintain a 2D boolean table where palindrome[i][j]
is true
if the substring s[i...j]
is a palindrome. Using this table, we calculate the minimum number of palindrome partitions.
Time Complexity: O(n^2) due to filling the palindrome table and computing cuts.
Space Complexity: O(n^2) as well for the DP tables storage.
1#include <vector>
2#include <string>
3#include <iostream>
4using namespace std;
5
6int minCut(string s) {
7 int n = s.size();
8 vector<vector<bool>> palindrome(n, vector<bool>(n, false));
9 vector<int> cuts(n, 0);
10
11 for (int i = 0; i < n; ++i) {
12 int min_cut = i;
13 for (int j = 0; j <= i; ++j) {
14 if (s[j] == s[i] && (i - j <= 2 || palindrome[j + 1][i - 1])) {
15 palindrome[j][i] = true;
16 min_cut = j == 0 ? 0 : min(min_cut, cuts[j - 1] + 1);
17 }
18 }
19 cuts[i] = min_cut;
20 }
21
22 return cuts[n - 1];
23}
24
25int main() {
26 string s = "aab";
27 cout << "Minimum cuts needed for Palindrome Partitioning: " << minCut(s) << endl;
28 return 0;
29}
In this C++ implementation, a vector of vectors is used to represent the palindrome table, and a separate vector is used for the cuts. The algorithm iterates through each end index of potential partitions and calculates the minimum cuts by checking if substrings are palindromes, utilizing previous results.
This approach utilizes the idea of expanding around potential palindrome centers, combined with a memoization strategy to store minimum cuts. It significantly reduces redundant calculations by only considering centers and keeping track of the best solutions observed so far.
Time Complexity: O(n^2) due to potentially expanding and updating cuts for each center.
Space Complexity: O(n) focused on the cuts array.
1
public class Solution {
private void ExtendPalindrome(string s, int start, int end, int[] dp) {
while (start >= 0 && end < s.Length && s[start] == s[end]) {
dp[end] = Math.Min(dp[end], start == 0 ? 0 : dp[start - 1] + 1);
start--;
end++;
}
}
public int MinCut(string s) {
int n = s.Length;
int[] dp = new int[n];
for (int i = 0; i < n; i++) dp[i] = i;
for (int center = 0; center < n; center++) {
ExtendPalindrome(s, center, center, dp);
ExtendPalindrome(s, center, center + 1, dp);
}
return dp[n - 1];
}
public static void Main(string[] args) {
Solution solution = new Solution();
Console.WriteLine("Minimum cuts using center expansion: " + solution.MinCut("aab"));
}
}
C# implementation draws on center-based expansion to curtail cut reductions via stored results that dynamically adjust as palindromes are confirmed through symmetry checks.