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;
}
相关推荐
哈哈不让取名字3 分钟前
基于C++的爬虫框架
开发语言·c++·算法
不忘不弃1 小时前
模拟内存分配器1
c语言
Lips6112 小时前
2026.1.20力扣刷题笔记
笔记·算法·leetcode
2501_941329722 小时前
YOLOv8-LADH马匹检测识别算法详解与实现
算法·yolo·目标跟踪
洛生&2 小时前
Planets Queries II(倍增,基环内向森林)
算法
小郭团队3 小时前
1_6_五段式SVPWM (传统算法反正切+DPWM2)算法理论与 MATLAB 实现详解
嵌入式硬件·算法·matlab·dsp开发
小郭团队3 小时前
1_7_五段式SVPWM (传统算法反正切+DPWM3)算法理论与 MATLAB 实现详解
开发语言·嵌入式硬件·算法·matlab·dsp开发
鱼跃鹰飞3 小时前
Leetcode347:前K个高频元素
数据结构·算法·leetcode·面试
bybitq3 小时前
LeetCode236-二叉树的最近公共祖先(LCA)问题详解-C++
算法·深度优先
啊阿狸不会拉杆3 小时前
《数字图像处理》第 7 章 - 小波与多分辨率处理
图像处理·人工智能·算法·计算机视觉·数字图像处理