using System;
namespace ConsoleApp11
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
GetHuiWen2("cbbd");
}
public static int GetHuiwen(string s, int left, int right, out int l, out int r)
{
l = -1;
r = -1;
while((left>=0 && right<s.Length ) && s[left] == s[right])
{
left--;
right++;
}
int len = right - left - 1;
if (len != 0)
{
l = left + 1;
r = right - 1;
}
return len;
}
public static void GetHuiWen2(string s)
{
if (s == null || s.Length <= 0) return;
int maxLen = 0;
int maxLeft = -1;
int maxRight = -1;
for(int i=0; i<s.Length; i++)
{
int l1, r1, l2, r2;
int tempLen1 = GetHuiwen(s, i, i, out l1, out r1);
int tempLen2 = GetHuiwen(s, i, i + 1, out l2, out r2);
if (tempLen1 > tempLen2)
{
if (tempLen1 > maxLen)
{
maxLen = tempLen1;
maxLeft = l1;
maxRight = r1;
}
}
else if (tempLen1 < tempLen2)
{
if(tempLen2 > maxLen)
{
maxLen = tempLen2;
maxLeft = l2;
maxRight = r2;
}
}
}
Console.WriteLine("Length: " + maxLen);
Console.WriteLine(string.Format("Value: {0}", s.Substring(maxLeft, maxRight - maxLeft + 1)));
}
}
}
求字符串中最长的回文字符串
最新推荐文章于 2023-02-07 18:58:22 发布
该代码实现了一个寻找给定字符串中最长回文子串的算法。它使用了双指针技术来检查字符串中可能的回文子串,并通过比较找到最长的回文子串。程序首先定义了一个辅助函数`GetHuiwen`用于检测是否为回文子串,然后在`GetHuiwen2`中遍历字符串并调用辅助函数,最终输出最长回文子串的长度和值。
984

被折叠的 条评论
为什么被折叠?



