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

所谓回文字符串,就是一个字符串,从左到右读和从右到左读是完全一样的。比如"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;
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值