添加 0005.最长回文子串.md C语言解法

This commit is contained in:
Guanzhong Pan
2022-01-24 08:57:02 +00:00
parent 454d50c072
commit fee948b2af

View File

@ -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;
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>