题目
Number: 5
Difficulty: Medium
Tags: String
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
题解
在字符串中找最长回文子串。
遍历字符串,每个字符同时向两边遍历,不相同就停止。时间复杂度O(N*N)
代码
string longestPalindrome(string s) {
if (s.size() < 2)
return s;
int len = s.size(), max_left = 0, max_len = 1, left, right;
for (int start = 0; start < len && len - start > max_len / 2;)
{
left = right = start;
while (right < len - 1 && s[right + 1] == s[right])
++right;
start = right + 1;
while (right < len - 1 && left > 0 && s[right + 1] == s[left - 1])
{
++right;
--left;
}
if (max_len < right - left + 1)
{
max_left = left;
max_len = right - left + 1;
}
}
return s.substr(max_left, max_len);
}