學渣帶你刷Leetcode0132分割回文串 II

題目描述

給定一個字符串 s,將 s 分割成一些子串,使每個子串都是迴文串。

返回符合要求的最少分割次數。

示例:

輸入: "aab"
輸出: 1
解釋: 進行一次分割就可將 s 分割成 ["aa","b"] 這樣兩個迴文子串。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/palindrome-partitioning-ii
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

白話題目:
 

算法:

 

詳細解釋關注 B站  【C語言全代碼】學渣帶你刷Leetcode 不走丟 https://www.bilibili.com/video/BV1C7411y7gB

C語言完全代碼

int minCut(char * s){
    int length = strlen(s);
    int left = 0;
    int right = 0;
    bool** ppbVolid = (bool**)malloc(length * sizeof(bool*));
    for (left = 0; left <= length - 1; left++)
    {
        ppbVolid[left] = (bool*)malloc(length * sizeof(bool));
        memset(ppbVolid[left], true, length * sizeof(bool));
    }

    int* pRes = (int*)malloc(length * sizeof(int));
    for (left = 0; left <= length - 1; left++)
    {
        pRes[left] = length;
    }

    for (int step = 1; step <= length - 1; step++)
    {
        for (left = 0, right = left + step; right <= length - 1; left++, right++)
        {
            ppbVolid[left][right] = (s[left] == s[right] && ppbVolid[left + 1][right - 1]);
        }
    }

    for (right = 0; right <= length - 1; right++)
    {
        if (ppbVolid[0][right])
        {
            pRes[right] = 0;
            continue;
        }

        for (left = 0; left <= right; left++)
        {
            if (ppbVolid[left][right])
            {
                pRes[right] = pRes[right] < pRes[left - 1] + 1 ? pRes[right] : pRes[left - 1] + 1;
            }
        }
    }

    return pRes[length - 1];
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章