mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 0005.最长回文子串.md C语言解法
This commit is contained in:
@ -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>
|
||||
|
Reference in New Issue
Block a user