5. Longest Palindromic Substring
https://leetcode.com/problems/longest-palindromic-substring/
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.
返回字符串中的最长回文子字符串
class Solution {
public:
string longestPalindrome(string s) {
string str;
str = changstr(s);
int len= str.length(),i;
int *p = new int[str.length() + 1];
memset(p, 0, sizeof(p));
int mx = 0, id = 1;
for (i = 1; i < len;i++)
{
if (mx > i)
{
p[i] = min( p[2 * id - i] , (mx- i));
}
else
{
p[i] = 1;
}
while (i - p[i]>0 &&i + p[i]<len&&str.at(i - p[i]) == str.at(i + p[i]))
p[i]++;
if (i + p[i] > mx)
{
mx = i + p[i];
id = i;
}
}
//最大回文字符串长度
int maxlen = 0, index =0;
for (int i = 0; i<len;i++)
{
if (p[i]>maxlen)
{
id = i;
maxlen = p[i];
}
}
string result;
for (i = id - p[id]+1;i < id+maxlen; i++)
{
if (str.at(i) != '#')
{
result += str.at(i);
}
}
return result;
}
string changstr(string str)
{
string str0;
str0 += "$#";
for (int i = 0; i < str.size(); i++)
{
str0 += str[i];
str0 += "#";
}
return str0;
}
};
以下内容来自LeetCode官网:
Approach #4 (Expand Around Center)[Accepted]
In fact, wecould solve it in O(n^2)O(n2) time usingonly constant space.
We observe thata palindrome mirrors around its center. Therefore, a palindrome can be expandedfrom its center, and there are only 2n - 12n−1 suchcenters.
You might be asking why there are 2n - 12n−1 butnot nn centers? The reason is the centerof a palindrome can be in between two letters. Such palindromes have evennumber of letters (such as ''abba''''abba'') and its center are between thetwo 'b''b's.
public String longestPalindrome(String s) {
int start = 0, end = 0;
for(int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s,i, i);
int len2 = expandAroundCenter(s,i, i + 1);
int len = Math.max(len1, len2);
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
returns.substring(start, end + 1);
}
privateintexpandAroundCenter(String s, int left, int right) {
int L = left, R = right;
while(L >= 0 &&R < s.length() && s.charAt(L) == s.charAt(R)) {
L--;
R++;
}
returnR - L - 1;
}