[let code]5.最长回文子串
the question:
analysis:
- you should find the last longest Palindrome like the frist instance “aba”;
- spilt the string ,and judge the substr;
- find the pos and longest length;
- return the right substr;
- this program just found the result , you should try to reduce the time and space complex.
code:
bool is(string s, int i, int j)
{
int t = i+j-1;
for (i; i <= t ; i++)
{
if (s[i] != s[t--])
return false;
}
return true;
}
string longestPalindrome(string s)
{
int pos = 0, max = 0, n = s.size();
for (int i = 0; i < n; i++)
{
for (int j = n - i; j >= 1; j--)
{
if (j >= max && is(s, i, j))
{
max = j;
pos = i;
}
}
}
return s.substr(pos, max);
}
result: