diff --git a/problems/0005.最长回文子串.md b/problems/0005.最长回文子串.md index 62c2cbde..4d48f184 100644 --- a/problems/0005.最长回文子串.md +++ b/problems/0005.最长回文子串.md @@ -615,6 +615,68 @@ char * longestPalindrome(char * s){ } ``` +C#: + +動態規則: +```c# +public class Solution { + + public string LongestPalindrome(string s) { + bool[,] dp = new bool[s.Length, s.Length]; + int maxlenth = 0; + int left = 0; + int right = 0; + for(int i = s.Length-1 ; i>=0; i--){ + for(int j = i; j maxlenth){ + maxlenth = j-i+1; + left = i; + right = j; + } + } + } + return s.Substring(left, maxlenth); + } +} +``` + +雙指針: +```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++; + } + } +} +``` +