題目:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.
Example 2:
Input: “cbbd”
Output: “bb”
解法一:
常規思路:
分爲奇數和偶數判斷,遍歷字符串,
(1) 如果 i 與 i+1 位置的字符相等,則向前一個以及向後一個 判斷是否相等,一次類推,知道不相等,記錄信息。
(2)如果 i 的前一個字符和後一個字符相同,則繼續判斷,直到不相同,記錄信息
(3)對比,查到最長迴文子串,按照奇偶構造返回字符串
代碼:
char * longestPalindrome(char * s){
int pos = 0;
char *res;
int len = 1;
int temp = 0;
int odd = 0;
bool flag = false;
for (int i = 0; s[i] != '\0'; i++)
{
temp = 0;
//偶數行爲
if ( s[i] == s[i+1] )
{
odd = 0;
while ((i - odd) >= 0 && (s[i + odd + 1]) != '\0')
{
if (s[i - odd] == s[i + 1 + odd])
{
odd++;
}
else
{
break;
}
if (odd >= len)
{
pos = i;
len = odd;
flag = true;
}
}
}
//奇數行爲
while ((i - temp) >= 0 && s[i + temp] != '\0')
{
if (s[i - temp] == s[i + temp])
{
temp++;
}
else
{
break;
}
if (temp > len)
{
pos = i;
len = temp;
flag = false;
}
}
}
int size =0;
int start = 0;
if (flag == true)
{
size = len * 2;
start = pos - len + 1;
}
else
{
len = len - 1;
size = 2 * len + 1;
start = pos - len;
}
res = (char*)malloc(size + 1);
for (int j = 0; j < size; j++,start++)
{
res[j] = s[start];
}
res[size] = '\0';
return res;
}
效率:
效率不是很好,還需要優化
針對上述解法,在大循環中,加入一個判斷,如果 i<total -len ,則挺住判斷,其中i是s的當前字符,total爲s的總長度,len爲當前最大回文字符串的一半的長度。 則效率提升20%。代碼如下:
char * longestPalindrome(char * s){
int pos = 0;
char *res;
int len = 1;
int temp = 0;
int odd = 0;
bool flag = false;
int total =0;
while(s[total]!='\0')
{
total++;
}
for (int i = 0; i < total -len ; i++) //在此處修改
{
temp = 0;
//偶數行爲
if ( s[i] == s[i+1] )
{
odd = 0;
while ((i - odd) >= 0 && (s[i + odd + 1]) != '\0')
{
if (s[i - odd] == s[i + 1 + odd])
{
odd++;
}
else
{
break;
}
if (odd >= len)
{
pos = i;
len = odd;
flag = true;
}
}
}
//奇數行爲
while ((i - temp) >= 0 && s[i + temp] != '\0')
{
if (s[i - temp] == s[i + temp])
{
temp++;
}
else
{
break;
}
if (temp > len)
{
pos = i;
len = temp;
flag = false;
}
}
}
int size =0;
int start = 0;
if (flag == true)
{
size = len * 2;
start = pos - len + 1;
}
else
{
len = len - 1;
size = 2 * len + 1;
start = pos - len;
}
res = (char*)malloc(size + 1);
for (int j = 0; j < size; j++,start++)
{
res[j] = s[start];
}
res[size] = '\0';
return res;
}
效率:
解法二:
思路:manacher算法