给你一个字符串 s,找到 s 中最长的回文子串。
示例 1:
输入:s = “babad”
输出:“bab”
解释:“aba” 同样是符合题意的答案。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring
using System;
namespace 最长回文子串进阶
{
class Program
{
static string myfun(string s)
{
int max = 0;
string res = "";
for (int i = 0; i < s.Length; i++)
{
for (int j = i; j < s.Length&&j <= i+1&&s[i]==s[j]; j++)
{
int x = i, y = j;
while (x - 1 >= 0 && y + 1 < s.Length)
{
if (s[x - 1] == s[y + 1])
{
x--;
y++;
}
else break;
}
if (max < y - x + 1)
{
max = y - x + 1;
res = s.Substring(x, y - x + 1);
}
}
}
return res;
}
static void Main(string[] args)
{
string str = Console.ReadLine();
Console.WriteLine(myfun(str));
}
}
}
要点说明
- 回文字符串说明:要么是p[i,i]开始左右相等然后逐步扩大长度,要么是p[i,i+1]&&s[i]==s[i+1] 开始左右相等然后逐步扩大长度。
- 子串截取:string.Substring(start,end)截取的字符串不包括end下标的字符
最笨的方法
- 理论上最简单,笨蛋都能想到,可是笨蛋无法实现。
- 直接代码获取字符串的所有子串,难度较大,一旦字符串较长,子串数量是
2^n数量级。然后判断所有子串是否是回文字符串,保留最长度的子串