您的位置:首页 > 其它

Longest Palindromic Substring 找最长的回文子字符串

2018-01-11 16:58 323 查看
所谓回文字符串,就是一个字符串,从左到右读和从右到左读是完全一样的。比如"level" 、 “aaabbaaa”

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.


Example:
Input: "cbbd"

Output: "bb"


个人(菜鸟)思路:

两个for循环,外层i从左向右,内层j右向左。如果s[i]==s[j],遍历i->j,是回文字符串就记录下来,不是的话继续j--。

C:

char* longestPalindrome(char* s) {
int maxlength = 0,length,temp = 1;
int i = 0,j = 0,x = 0,k = 0;
int i_flag = 0,j_flag = 0,flag;

while(s[i] != NULL){
i++;
}
length = i;

for(i = 0 ;i < length; i++){
for(j = length - 1;j > i; ){
if(s[i] == s[j]){
flag = true;
x = i;
k = j;
while(x <= k){
if(s[x] != s[k])
flag = false;
x++;
k--;
}
if(flag == true){
if(maxlength < (j - i + 1)){
i_flag = i;
j_flag = j;
maxlength = (j - i + 1);
}
break;
} else{
j--;
}
}else{
j--;
}
}
}

if(maxlength == 0){
char *non_result = (char *)malloc(sizeof(char));
non_result[0] = s[0];
return non_result;
}else{
if(maxlength == length)
return s;
else{
char *result = (char *)malloc(sizeof(char)* (j_flag - i_flag + 1));

for(i = i_flag, j = 0; i <= j_flag ; i++,j++){
result[j] = s[i];
}
result[j] = '\0';
return result;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: