题目
给定一个字符串s, 找到s中最长的回文子串。你可以假设s的最大长度为1000.
class Palindrome
{
public static string FindLongestSubPalindromeStr(string sourceStr)
{
string dstStr = "";
if(sourceStr.Length == 0)
return dstStr;
for(int centerIndex = 0; centerIndex<sourceStr.Length; centerIndex++)
{
string curStr = sourceStr[centerIndex].ToString();
int left = centerIndex - 1;
int right = centerIndex + 1;
//判断奇数
while(left>=0 && right<sourceStr.Length)
{
if(sourceStr[left] != sourceStr[right])
break;
else
{
curStr = sourceStr.SubString(left, right-left+1);
left--;
right++;
}
}
if(curStr.Length > dstStr.Length)
{
dstStr = curStr;
}
//判断偶数
int middleRight = centerIndex + 1;
if(middleRight >=sourceStr.Length)
continue;
if(sourceStr[centerIndex] != sourceStr[middleRight])
continue;
left = centerIndex - 1;
right = middleRight + 1;
while(left>=0 && right<sourceStr.Length)
{
if(sourceStr[left] != sourceStr[right])
break;
else
{
curStr = sourceStr.SubString(left, right-left+1);
left--;
right++;
}
}
if(curStr.Length > dstStr.Length)
{
dstStr = curStr;
}
}
return dstStr;
}
}