LeetCode //C - 1278. Palindrome Partitioning III

1278. Palindrome Partitioning III

You are given a string s containing lowercase letters and an integer k. You need to :

  • First, change some characters of s to other lowercase English letters.
  • Then divide s into k non-empty disjoint substrings such that each substring is a palindrome.

Return the minimal number of characters that you need to change to divide the string.

Example 1:

Input: s = "abc", k = 2

Output: 1

Explanation: You can split the string into "ab" and "c", and change 1 character in "ab" to make it palindrome.

Example 2:

Input: s = "aabbc", k = 3

Output: 0

Explanation: You can split the string into "aa", "bb" and "c", all of them are palindrome.

Example 3:

Input: s = "leetcode", k = 8

Output: 0

Constraints:
  • 1 <= k <= s.length <= 100.
  • s only contains lowercase English letters.

From: LeetCode

Link: 1278. Palindrome Partitioning III


Solution:

Ideas:

Precompute the cost to convert every substring into a palindrome, then use dynamic programming to find the minimum cost of splitting the string into exactly k parts.

Code:
c 复制代码
#include <string.h>
#include <limits.h>

int palindromePartition(char* s, int k) {
    int n = strlen(s);

    // cost[i][j] = minimum changes needed to make s[i..j] a palindrome
    int cost[100][100] = {0};

    for (int length = 2; length <= n; length++) {
        for (int i = 0; i + length <= n; i++) {
            int j = i + length - 1;

            cost[i][j] = cost[i + 1][j - 1];

            if (s[i] != s[j]) {
                cost[i][j]++;
            }
        }
    }

    // dp[parts][i] = minimum changes to split first i characters
    // into exactly parts palindromic substrings
    int dp[101][101];

    for (int parts = 0; parts <= k; parts++) {
        for (int i = 0; i <= n; i++) {
            dp[parts][i] = INT_MAX / 2;
        }
    }

    dp[0][0] = 0;

    for (int parts = 1; parts <= k; parts++) {
        for (int i = parts; i <= n; i++) {
            for (int split = parts - 1; split < i; split++) {
                int current =
                    dp[parts - 1][split] + cost[split][i - 1];

                if (current < dp[parts][i]) {
                    dp[parts][i] = current;
                }
            }
        }
    }

    return dp[k][n];
}
相关推荐
Godspeed Zhao40 分钟前
现代智能雷达技术18——算法(4)
算法
CHEEVEN_QY1 小时前
液冷板热阻计算与流阻优化的实战方法
人工智能·算法·机器学习
殷色玫瑰2 小时前
C/C++ 内存管理详解:从内存分布到 new/delete 底层原理
java·linux·c语言·c++
C++ 老炮儿的技术栈2 小时前
不一样的数值交换
数据结构·c++·人工智能·算法·c·csdn开发云
C++ 老炮儿的技术栈2 小时前
main函数之后的调用
c语言·c++·人工智能·qt·mfc·c
hahaha60163 小时前
Shades-of-Gray (SoG) 算法--白平衡算法
人工智能·嵌入式硬件·算法·计算机视觉
青山木3 小时前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
夊4 小时前
C语言第十一课:指针(五)
算法
小师兄吃牛肉4 小时前
C语言指针进阶全解析
java·c语言·算法