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:
@ -513,5 +513,41 @@ char * longestPalindrome(char * s){
|
||||
}
|
||||
```
|
||||
|
||||
双指针:
|
||||
```c
|
||||
int left, maxLength;
|
||||
void extend(char *str, int i, int j, int size) {
|
||||
while(i >= 0 && j < size && str[i] == str[j]) {
|
||||
//若当前子字符串长度大于最长的字符串长度,进行更新
|
||||
if(j - i + 1 > maxLength) {
|
||||
maxLength = j - i + 1;
|
||||
left = i;
|
||||
}
|
||||
//左指针左移,右指针右移。扩大搜索范围
|
||||
++j, --i;
|
||||
}
|
||||
}
|
||||
|
||||
char * longestPalindrome(char * s){
|
||||
left = right = maxLength = 0;
|
||||
int size = strlen(s);
|
||||
|
||||
int i;
|
||||
for(i = 0; i < size; ++i) {
|
||||
//长度为单数的子字符串
|
||||
extend(s, i, i, size);
|
||||
//长度为双数的子字符串
|
||||
extend(s, i, i + 1, size);
|
||||
}
|
||||
|
||||
//复制子字符串
|
||||
char *subStr = (char *)malloc(sizeof(char) * (maxLength + 1));
|
||||
memcpy(subStr, s + left, maxLength);
|
||||
subStr[maxLength] = 0;
|
||||
|
||||
return subStr;
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<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