动态规划之最长回文子串

回文子串基本是动态规划里面的应用示例之一。虽然在实际中或者网上,我没有找到回文子串的使用案例。

#include <stddef.h>
#include <stdio.h>
#include <string.h>

void longestPalindrome(char str[100],size_t len)
{
    if (len < 0) return;
    char res[100] = {};
    res[0] = str[0];
    int dp[len][len] = {0};

    for (int i=0;i<len;i++)
    {
        dp[i][i] = 1;
    }
    for (int j=1;j<len;j++)
    {
        for (int i=0;i<j;i++) 
        {
            if (j-i==1 && str[i] == str[j])
            {
                dp[i][j] = 1;
            } else if (str[i] == str[j] && dp[i+1][j-1]) {
                dp[i][j] = 1;
            }
            // 获取最长回文子串
            if (dp[i][j] && j-i+1>strlen(res)) {
                memset(res,0,100);
                strncpy(res,str+i,j+1);
            }
        }
    }
    printf("%s\n",res);
}

int main(int argc,char *argv[])
{
    char str[]="memset from longestPi, thsi hash a big ababa";
    longestPalindrome(str,strlen(str));
}

 

posted @ 2024-01-03 09:48  zhjh256  阅读(5)  评论(0编辑  收藏  举报