From 3a46ffdad4cfcc2bc3695db93f4760b9ae70b4d2 Mon Sep 17 00:00:00 2001 From: Guanzhong Pan Date: Tue, 25 Jan 2022 12:54:50 +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?=E5=8F=8C=E6=8C=87=E9=92=88=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0005.最长回文子串.md | 36 +++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/problems/0005.最长回文子串.md b/problems/0005.最长回文子串.md index 588afc22..99458825 100644 --- a/problems/0005.最长回文子串.md +++ b/problems/0005.最长回文子串.md @@ -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; +} +``` + -----------------------