题目描述:
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.
Given the string = "abcdzdcab"
, return "cdzdc"
.
O(n2) time is acceptable. Can you do it in O(n) time.
这题我打算对于每个ch,都以它为中心看看能得到的palindromic有多长,然后取最长的那个substr。这里有一个trick:由于string length有odd和even之分,如果以一个ch为中心,得到的string就会总是奇数长度;那如果以两个ch为中心,算起来就比较麻烦了。所以,这里在string的两边和每个ch中间都插入‘#’,这样把整个string都转化成一个奇数长度的string,并且保证它的palindromic性质不变,就很容易处理了。
得到substr以后,再把‘#’从中删去,就是我们想要的答案了。
Mycode(AC = 43ms):
class Solution {
public:
/**
* @param s input string
* @return the longest palindromic substring
*/
string longestPalindrome(string& s) {
// Write your code here
// insert '#' in between each char in s
int idx = 0, max_length = 1;
string ext = "#";
while (idx < s.length()) {
ext += s[idx++];
ext += "#";
}
// find the longest palindromic for each i
// with i as center of the palindromic
string substr = "";
for (int i = 1; i < ext.length(); i++) {
int count = 0;
string tmp = "";
while (i - count >= 0 && i + count < ext.length() &&
ext[i - count] == ext[i + count])
{
tmp = ext.substr(i - count, 1 + 2 * count);
count++;
}
max_length = max(max_length, (int)tmp.length());
substr = tmp.length() == max_length? tmp : substr;
}
// remove '#' in the substr, that's the answer
string ans = "";
for (int i = 0; i < substr.length(); i++) {
if (substr[i] != '#') {
ans += substr[i];
}
}
return ans;
}
};