Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 2472. Maximum Number of Non-overlapping Palindrome Substrings

Rain Hu

2472. Maximum Number of Non-overlapping Palindrome Substrings


一、題目

You are given a string s and a positive integer k. Select a set of non-overlapping substrings from the string s that satisfy the following conditions:

Example 1:

Example 2:

Constraints:


二、分析

三、解題

1. DP

int maxPalindromes(string s, int k) {
    int n = s.length();
    vector<vector<bool>> dp(n, vector<bool>(n, false));
    int left, right;
    int len = 0;
    int res = 0;
    int pos = 0;
    for (int j = 0; j < n; j++){
        for (int i = 0; i <= j; i++){
            if (i == j){
                dp[i][j] = true;
            } else if (j - i == 1){
                dp[i][j] = s[i] == s[j];
            } else {
                dp[i][j] = (s[i] == s[j] && dp[i+1][j-1]);
            }
            if (dp[i][j] && j - i + 1 >= k && i >= pos) {
                pos = j+1;
                res++;
            }
        }
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 328. Odd Even Linked List
Next
[LeetCode] 2471. Minimum Number of Operations to Sort a Binary Tree by Level