leetcode 5 查找最长的回文子串

时间:2022-07-06 01:32:33

给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

示例 1:

输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。

示例 2:

输入: "cbbd"
输出: "bb"
public static  string LongestPalindrome(string s)
{
string result = "";
if(string.IsNullOrWhiteSpace(s))
{
return s;
} if(s.Length == || s.Length > )
{
return s;
} else if(s.Length == )
{
if(IsHuiZiChuan(s))
{
return s;
}
else
{
return s[].ToString();
}
} List<string> listTmp = new List<string>();
int maxCount = ;
for(int i=;i<s.Length -;i++)
{
string si = s[i].ToString();
for (int j=i+;j<s.Length;j++)
{
si += s[j];
if(IsHuiZiChuan(si))
{
listTmp.Add(si);
if(si.Length > maxCount)
{
maxCount = si.Length;
result = si;
}
}
else
{
continue;
}
}
}
if(result == "")
{
return s[].ToString();
} return result;
} public static bool IsHuiZiChuan(string str)
{
if(str.Length == )
{
return true;
} for (int i = ; i < (str.Length / ); i++)
{
if(str[i] != str[str.Length - i -])
{
return false;
} }
return true; }

代码可以执行,但是时间和空间复杂度不佳,还需要进一步优化。