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];
}
相关推荐
another heaven16 小时前
【C/C++ Ranges 是零开销抽象吗?拆开管道、惰性求值和编译期膨胀】
c语言·开发语言·c++
Code_Solitude16 小时前
C语言动态内存 + 柔性数组 + 数组名退化
c语言·算法·柔性数组
上海潭龙东海科技有限公司16 小时前
客运站管控之动态孪生技术方案(新增一屏管控模块
数据仓库·人工智能·算法·重构·动态规划
文丑颜不良啊17 小时前
LeetCode2821~2840题目解析
java·leetcode
YLCHUP19 小时前
【思维&图论建模】题解:债权(debt)_图论_建模_思路转化_思维题目_C++算法竞赛
c++·笔记·算法·数学建模·贪心算法·深度优先·图论
思麟呀19 小时前
背包DP(01背包+完全背包)
c++·算法
Zwawa20 小时前
让屏幕动起来:OLED动画效果,丝滑光标、帧动画和一只贪吃蛇
c语言·单片机·嵌入式
笑容掩饰我的失落20 小时前
区块链从小白到精通(七):Solidity 语法精讲——数据类型、函数、修饰器与事件
算法·区块链·php·智能合约·哈希算法
Pniubi21 小时前
力扣24. 两两交换链表中的节点(递归)
算法·leetcode·链表