Split string into minimal number of strings where each letter is repeated an odd number of times

Viewed 225

For example, the string "abab" requires one split into two strings : "ab" and "ab" so the answer is 1 and the string "ababab" does not require any splits so the answer is 0.

I came up with a solution that checks for each substring the condition and stores the result in a boolean matrix and then fills an int matrix so that it finds the minimal number of splits. Any thoughts on how I can make the algorithm faster?

bool condition(const int count[]) {
    for (int i = 0; i <= 25; i++){
        if (count[i] != 0 && count[i] % 2 == 0) {
            return false;
        }
    }
    return true;
}



int minPartion(std::string& str)
{
    int n = str.size();


    int i, j, k, L;

    int** even = new int*[n];
    for(int i = 0; i < n; ++i)
        even[i] = new int[n];

    int** minSplits = new int*[n];
    for(int i = 0; i < n; ++i)
        minSplits[i] = new int[n];

    for (i = 0; i < n; i++)
    {
        even[i][i] = true;
        minSplits[i][i] = 0;
    }


    for (int i = 0; i < n; i++) {
        int count2[26] = {0};
        for (int j = i; j < n; j++) {
            count2[str[j] - 'a']++;
            even[i][j] = condition(count2);
        }
    }



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

            if (even[i][j])
                minSplits[i][j] = 0;
            else
            {
                minSplits[i][j] = INT_MAX;
                for (k = i; k <= j - 1; k++)
                    minSplits[i][j] = min(minSplits[i][j], minSplits[i][k] + minSplits[k + 1][j] + 1);
            }
        }
    }
    
    return minSplits[0][n - 1];
}
1 Answers

An easy place to start would be to pack the count array into two 32-bit words, one representing which values are nonzero and one representing which values are odd. You can update these with |= uint32_t{1} << (letter - 'a') and ^= uint32_t{1} << (letter - 'a') respectively, then condition becomes a simple equality test.

Related