From 4621def631c57ff5fe0c360185268fd9813b71b2 Mon Sep 17 00:00:00 2001 From: Min Date: Wed, 30 Nov 2022 23:11:47 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A00005.=E6=9C=80=E9=95=B7?= =?UTF-8?q?=E5=9B=9E=E6=96=87=E5=AD=90=E4=B8=B2C#=20=E9=9B=99=E6=8C=87?= =?UTF-8?q?=E9=87=9D=E7=9A=84=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0005.最长回文子串.md | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0005.最长回文子串.md b/problems/0005.最长回文子串.md index 84d8d835..4d48f184 100644 --- a/problems/0005.最长回文子串.md +++ b/problems/0005.最长回文子串.md @@ -647,6 +647,36 @@ public class Solution { } ``` +雙指針: +```C# +public class Solution { + int maxlenth = 0; + int left = 0; + int right = 0; + + public string LongestPalindrome(string s) { + int result = 0; + for (int i = 0; i < s.Length; i++) { + extend(s, i, i, s.Length); // 以i為中心 + extend(s, i, i + 1, s.Length); // 以i和i+1為中心 + } + return s.Substring(left, maxlenth); + } + + private void extend(string s, int i, int j, int n) { + while (i >= 0 && j < n && s[i] == s[j]) { + if (j - i + 1 > maxlenth) { + left = i; + right = j; + maxlenth = j - i + 1; + } + i--; + j++; + } + } +} +``` +