Merge pull request #1789 from Min-987/master

增加0005.最長回文子串C# 的版本
This commit is contained in:
程序员Carl
2022-12-22 11:12:44 +08:00
committed by GitHub

View File

@ -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 <s.Length;j++){
if(s[i] == s[j]){
if(j - i <= 1){ // 情况一和情况二
dp[i, j] = true;
}else if( dp[i+1, j-1] ){ // 情况三
dp[i, j] = true;
}
}
if(dp[i, j] && j-i+1 > 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++;
}
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>