LeetCode //C - 5. Longest Palindromic Substring

5. Longest Palindromic Substring

Given a string s, return the longest palindromicsubstring in s.

Example 1:

Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.

Example 2:

Input: s = "cbbd"
Output: "bb"

Constraints:
  • 1 <= s.length <= 1000
  • s consist of only digits and English letters.

From: LeetCode

Link: 5. Longest Palindromic Substring


Solution:

Ideas:
  1. Expand Around Center: We'll create a helper function, expandFromCenter, to find the length of the palindrome by expanding around its center. This function will handle both odd and even length palindromes.

  2. Iterate Over the String: For each character in the string, we'll use expandFromCenter to check for the longest palindrome centered at that character.

  3. Update the Longest Palindrome: We'll keep track of the longest palindrome we've found so far.

  4. Return the Longest Palindrome: We'll use dynamic memory allocation to create a substring for the longest palindrome and return it.

Code:
c 复制代码
// Helper function to expand from the center and find palindrome length
int expandFromCenter(char* s, int left, int right) {
    while (left >= 0 && right < strlen(s) && s[left] == s[right]) {
        left--;
        right++;
    }
    return right - left - 1;
}

char* longestPalindrome(char* s) {
    if (s == NULL || strlen(s) < 1) return "";

    int start = 0, end = 0;
    for (int i = 0; i < strlen(s); i++) {
        int len1 = expandFromCenter(s, i, i); // Odd length palindromes
        int len2 = expandFromCenter(s, i, i + 1); // Even length palindromes
        int len = len1 > len2 ? len1 : len2;

        if (len > end - start) {
            start = i - (len - 1) / 2;
            end = i + len / 2;
        }
    }

    char* result = malloc(end - start + 2);
    strncpy(result, s + start, end - start + 1);
    result[end - start + 1] = '\0';
    return result;
}
相关推荐
kkeeper~6 小时前
0基础C语言积跬步之数据在内存中的存储
c语言·数据结构·算法
wabs6668 小时前
关于贪心算法的一些自我总结【力扣45.跳跃游戏II】【灵感来源:代码随想录】
算法·贪心算法·复盘
2401_876964138 小时前
【湖北专升本】2026湖北专升本真题PDF+备考资料汇总
数据结构·人工智能·经验分享·深度学习·算法·计算机视觉
qq3862461968 小时前
更新补发第6天:7天学会C语言,每天5分钟,不需要基础
c语言·for循环·循环语句·while循环·do-while循环
嗝o゚8 小时前
CANN GE 算子融合——融合算法与调度策略
算法·昇腾·cann·ge
小江的记录本9 小时前
【JVM虚拟机】垃圾回收GC:垃圾回收算法:标记-清除、标记-复制、标记-整理、分代收集(附《思维导图》+《面试高频考点清单》)
java·jvm·后端·python·算法·安全·面试
Ulyanov10 小时前
用声明式语法重新定义Python桌面UI:QML+PySide6现代开发入门(一)
开发语言·python·算法·ui·系统仿真·雷达电子对抗仿真
数据科学小丫10 小时前
特征工程处理
人工智能·算法·机器学习
z落落11 小时前
C#参数区别
java·算法·c#
c2385611 小时前
vector(下)
数据结构·算法