流程
定义 bool二维数组作为子项状态。以长度分子项判断。
长度为1时,全为true
长度为2时,判断首尾是否相同
4. 长度为3时,判断首尾和子项状态
5.后续同理,黄色点为首尾和子项
最终判断条件,当前状态为true,且当前长度比上一次true状态长度长。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCode05
{
class Program
{
static void Main(string[] args)
{
string str = LongestPalindrome("babad");
}
static public string LongestPalindrome(string s)
{
int len = s.Length;
bool[,] status = new bool[len,len];
string result = "";
for (int i = 1; i <=len; i++)
{
for (int start = 0; start < len; start++)
{
int end = start + i - 1;
if (end >= len)
break;
status[start, end] = (i == 1 || i == 2 || status[start + 1,end-1] )&& s[start] ==s[end];
if(status[start, end] && i>result.Length)
{
result = s.Substring(start, i);
}
}
}
return result;
}
static public string LongestPalindrome2(string s)
{
int len = s.Length;
if (len < 2)
{
return s;
}
int begin = 0, maxLen = 1;
for (int i = 0; i < len; i++)
{
int l = Math.Max(_LongestPalindrome(i, i), _LongestPalindrome(i, i + 1));
if (l > maxLen)
{
begin = i - (l - 1) / 2;
maxLen = l;
}
}
return s.Substring(begin, maxLen);
int _LongestPalindrome(int left, int right)
{
while (left >= 0 && right < s.Length && s[left] == s[right])
{
left--;
right++;
}
return right - left - 1;
}
}
}
}