LeetCode:C语言 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

百度了一下关于C语言的实现比较少,遂发出来自己实现的C语言版本。这个实现的也不太好,勉强能过LeetCode

C语言实现:

给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

示例 1:

输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2:

输入: "cbbd"
输出: "bb"

思路

for循环字符,while循环比较该字符串两边的字符串是否相等
退出条件是,左边界小于0,有边界大于字符串长度,左字符不等于右字符。

char * longestPalindrome(char * s){
  if (strlen(s) < 2) {
        return s;
    }
    int start = 0, end = 0;
    for (int i = 0; i < strlen(s); i++) {
        int temp_s = i, temp_e = i;
        // 中间对称型
        while (temp_s >= 0 && temp_e < strlen(s) && s[temp_s] == s[temp_e]) {
            temp_s--;
            temp_e++;
        }
        // 最后一步不符合回退
        temp_s++;
        temp_e--;
        if (temp_e - temp_s > end - start) {
            start = temp_s;
            end = temp_e;
        }
        
        if (i + 1 < strlen(s) && s[i] == s[i + 1]) {
            // 两边对称型
            int temp_s = i, temp_e = i+1;
            while (temp_s >= 0 && temp_e < strlen(s) && s[temp_s] == s[temp_e]) {
                temp_s--;
                temp_e++;
            }
            // 最后一步不符合回退
            temp_s++;
            temp_e--;
            if (temp_e - temp_s > end - start) {
                start = temp_s;
                end = temp_e;
            }
        }
    }
    char *sub_s = malloc((end - start + 1) * sizeof(char*));
    strncpy(sub_s, s + start, end - start + 1);
    sub_s[end - start + 1] = '\0';
    return sub_s;
}

最后

这个回文有两种情况,中间对称:sdsds,两边对称:sdds。但是对于cccs,这种就没办法判断是属于哪种了,所以写了两个while循环,有待优化。欢迎大家评论!

你可能感兴趣的:(LeetCode:C语言 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。)