给你一个字符串 s,找到 s 中最长的回文子串。
s = a return a
s = abbad return abba
这一题有多种解法,我们先看暴力解法:用滑窗, 双指针 End start 对比
如果End -start 之间的字符串是回文就记录下来,且保存下来长度,对比下一个是否长度比已求出的长,如果是,就保存下来,不是就继续。
static char tmpstring[1001] = “\0”;
static bool flag = false;
bool Padlindrome(char* s, int start,int end)
{
memset(tmpstring, '\0', 1001);
int count = 0;
int tmpstart = start;
int tmpend = end;
if (s == NULL) {
return false;
}
if (start == end) {
tmpstring[0] = s[start];
return true;
}
while (start <= end) {
if (s[start] != s[end]) {
return false;
}
start++;
end--;
}
while (tmpstart <= tmpend) {
tmpstring[count] = s[tmpstart];
count++;
tmpstart++;
}
return true;
}
char* longestPalindrome(char * s) {
int start = 0;
int end = 0;
int length = 0;
char* ret = (char*)malloc(sizeof(char)*1001);
// ret =s;
for (int start = 0; start < strlen(s); start++) {
for (int end = start; end < strlen(s); end++) {
if (Padlindrome(s, start, end)) {
//calculate length
if (length <= (end - start)) {
length = end - start;
strcpy(ret,tmpstring);
}
}
}
}
}
return ret;
}
```如果这样的话会有一个问题,超时。怎么办呢?第一步优化,如果后面的End-Start的长度小于Length,就直接往下走:
```c
static char tmpstring[1001] = "\0";
static bool flag = false;
bool Padlindrome(char* s, int start,int end)
{
memset(tmpstring, '\0', 1001);
int count = 0;
int tmpstart = start;
int tmpend = end;
if (s == NULL) {
return false;
}
if (start == end) {
tmpstring[0] = s[start];
return true;
}
while (start <= end) {
if (s[start] != s[end]) {
return false;
}
start++;
end--;
}
while (tmpstart <= tmpend) {
tmpstring[count] = s[tmpstart];
count++;
tmpstart++;
}
return true;
}
char* longestPalindrome(char * s) {
int start = 0;
int end = 0;
int length = 0;
char* ret = (char*)malloc(sizeof(char)*1001);
// ret =s;
for (int start = 0; start < strlen(s); start++) {
for (int end = start; end < strlen(s); end++) {
i**f(length<=(end-start)){**
if (Padlindrome(s, start, end)) {
//calculate length
if (length <= (end - start)) {
length = end - start;
strcpy(ret,tmpstring);
}
}
**}**
}
}
return ret;
}
```加了一个简单的条件判断,就不会超时了,但是效率还是很低。下面会讲一下继续优化的办法,动态规划