Given a string s, find the longest palindromic substring in s, you may assume that the maximun length of s is 1000.
/*
* Given a string s, find the longest palindromic substring in s,
* you may assume that the maximun length of s is 1000.
*
* Input : "babad"
* Output : "bab"
*
* Input : "cbbd"
* Output : "bb"
*
* Input : "aacabdkacaa"
* Output : "aca"
*
* Input : "abacab"
* Output : "bacab"
*/
public string LeetCode_5(string s)
{
string maxStr = "";
int left = 0, rigth = 0;
if (s == null || s.Length == 0)
return "";
for (int i = 0; i < s.Length; i++)
{
//偶數長度
left = i; rigth = i;
while ((left >= 0) && (rigth < s.Length) && (s.Substring(left, 1) == s.Substring(rigth, 1)))
{
if (maxStr.Length < s.Substring(left, rigth - left+1).Length)
{
maxStr = s.Substring(left, rigth - left+1);
}
left--;
rigth++;
}
//奇數長度
left = i; rigth = i + 1;
while ((left >= 0) && (rigth < s.Length) && (s.Substring(left, 1) == s.Substring(rigth, 1)))
{
if (maxStr.Length < s.Substring(left, rigth - left+1).Length)
{
maxStr = s.Substring(left, rigth - left+1);
}
left--;
rigth++;
}
}
return maxStr;
}