mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
@ -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"/>
|
||||
|
Reference in New Issue
Block a user