0.声明
该题目来源于LeetCode
如有侵权,立马删除。
解法不唯一,如有新解法可一同讨论。
1.题目
0005最长回文子串
给你一个字符串s,找到s中最长的回文子串。
如果字符串的反序与原始字符串相同,则该字符串称为回文字符串。
示例 1:
输入:s = “babad”
输出:“bab”
解释:“aba” 同样是符合题意的答案。
示例 2:
输入:s = “cbbd”
输出:“bb”
提示:
1 <= s.length <= 1000
s 仅由数字和英文字母组成
2.代码
namespace LeetCode_0005最长回文子串
{
internal class Program
{
static void Main(string[] args)
{
string s = "babad";
LeetCode_LongestPalindrome llp = new LeetCode_LongestPalindrome();
string s_Result = llp.LongestPalindrome(s);
Console.WriteLine(s_Result);
Console.ReadKey();
}
}
class LeetCode_LongestPalindrome
{
public string LongestPalindrome(string s)
{
int n = s.Length;
bool[,] P = new bool[n, n];
string s_Rsult = "";
//遍历所有的长度
for (int i = 1; i <= n; i++)
{
for (int j = 0; j < n; j++)
{
int i_End = j + i - 1;
if (i_End >= n)
break;
//长度为1和2 单独判断
P[j, i_End] = (i == 1 || i == 2 || P[j + 1, i_End - 1]) && s[j] == s[i_End];
if (P[j, i_End] && i > s_Rsult.Length)
s_Rsult = s.Substring(j, i);
}
}
return s_Rsult;
}
}
}