From fee948b2af53b7bfc583fbbe5c43cd98c04e462f Mon Sep 17 00:00:00 2001 From: Guanzhong Pan Date: Mon, 24 Jan 2022 08:57:02 +0000 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200005.=E6=9C=80=E9=95=BF?= =?UTF-8?q?=E5=9B=9E=E6=96=87=E5=AD=90=E4=B8=B2.md=20C=E8=AF=AD=E8=A8=80?= =?UTF-8?q?=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0005.最长回文子串.md | 49 +++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/problems/0005.最长回文子串.md b/problems/0005.最长回文子串.md index f204a607..588afc22 100644 --- a/problems/0005.最长回文子串.md +++ b/problems/0005.最长回文子串.md @@ -462,7 +462,56 @@ var longestPalindrome = function(s) { }; ``` +## C +动态规划: +```c +//初始化dp数组,全部初始为false +bool **initDP(int strLen) { + bool **dp = (bool **)malloc(sizeof(bool *) * strLen); + int i, j; + for(i = 0; i < strLen; ++i) { + dp[i] = (bool *)malloc(sizeof(bool) * strLen); + for(j = 0; j < strLen; ++j) + dp[i][j] = false; + } + return dp; +} +char * longestPalindrome(char * s){ + //求出字符串长度 + int strLen = strlen(s); + //初始化dp数组,元素初始化为false + bool **dp = initDP(strLen); + int maxLength = 0, left = 0, right = 0; + + //从下到上,从左到右遍历 + int i, j; + for(i = strLen - 1; i >= 0; --i) { + for(j = i; j < strLen; ++j) { + //若当前i与j所指字符一样 + if(s[i] == s[j]) { + //若i、j指向相邻字符或同一字符,则为回文字符串 + if(j - i <= 1) + dp[i][j] = true; + //若i+1与j-1所指字符串为回文字符串,则i、j所指字符串为回文字符串 + else if(dp[i + 1][j - 1]) + dp[i][j] = true; + } + //若新的字符串的长度大于之前的最大长度,进行更新 + if(dp[i][j] && j - i + 1 > maxLength) { + maxLength = j - i + 1; + left = i; + right = j; + } + } + } + //复制回文字符串,并返回 + char *ret = (char*)malloc(sizeof(char) * (maxLength + 1)); + memcpy(ret, s + left, maxLength); + ret[maxLength] = 0; + return ret; +} +``` -----------------------