All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g1101_1200.s1147_longest_chunked_palindrome_decomposition.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g1101_1200.s1147_longest_chunked_palindrome_decomposition;

// #Hard #String #Dynamic_Programming #Greedy #Two_Pointers #Hash_Function #Rolling_Hash
// #2023_06_01_Time_2_ms_(60.00%)_Space_43.4_MB_(20.00%)

/**
 * 1147 - Longest Chunked Palindrome Decomposition\.
 *
 * Hard
 *
 * You are given a string `text`. You should split it to k substrings (subtext1, subtext2, ..., subtextk) such that:
 *
 * *   subtexti is a **non-empty** string.
 * *   The concatenation of all the substrings is equal to `text` (i.e., subtext1 + subtext2 + ... + subtextk == text).
 * *   subtexti == subtextk - i + 1 for all valid values of `i` (i.e., `1 <= i <= k`).
 *
 * Return the largest possible value of `k`.
 *
 * **Example 1:**
 *
 * **Input:** text = "ghiabcdefhelloadamhelloabcdefghi"
 *
 * **Output:** 7
 *
 * **Explanation:** We can split the string on "(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)".
 *
 * **Example 2:**
 *
 * **Input:** text = "merchant"
 *
 * **Output:** 1
 *
 * **Explanation:** We can split the string on "(merchant)".
 *
 * **Example 3:**
 *
 * **Input:** text = "antaprezatepzapreanta"
 *
 * **Output:** 11
 *
 * **Explanation:** We can split the string on "(a)(nt)(a)(pre)(za)(tpe)(za)(pre)(a)(nt)(a)".
 *
 * **Constraints:**
 *
 * *   `1 <= text.length <= 1000`
 * *   `text` consists only of lowercase English characters.
**/
public class Solution {
    public int longestDecomposition(String text) {
        int n = text.length();
        int l = 0;
        int r = n - 1;
        int len = 1;
        int ans = 0;
        String lft;
        String rit;
        boolean perfectSubstring = false;
        while (l + len <= r - len + 1) {
            lft = text.substring(l, l + len);
            rit = text.substring(r - len + 1, r + 1);
            if (lft.equals(rit)) {
                ans += 2;
                if (l + len == r - len + 1) {
                    perfectSubstring = true;
                    break;
                }
                l = l + len;
                r = r - len;
                len = 1;
            } else {
                len++;
            }
        }
        if (!perfectSubstring) {
            ans++;
        }
        return ans;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy