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++; + } + } +} +``` +