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;
}
相关推荐
sylviiiiiia1 分钟前
Leetcode hot100 多数元素/相交链表/反转链表
算法·leetcode·链表
CoderYanger4 分钟前
A.每日一题:3622. 判断整除性
java·程序人生·算法·leetcode·面试·职场和发展·蓝桥杯
rannn_11113 分钟前
【力扣hot100】动态规划专题|70、118、198、279、322、139、300、152、416、32
算法·leetcode·动态规划
渡之14 分钟前
ArduPilot(APM)滤波器之 HarmonicNotchFilter 深度解析
算法·无人机
我不会起名字32214 分钟前
一天一道算法题(26):栈的简单应用
java·数据结构·python·算法·leetcode·golang·
susplus19 分钟前
【HTTP协议】HTTP介绍及基础【C语言爬虫实现】
c语言·爬虫·http·万维网
lvwangshu43 分钟前
exBSGS 算法
数学·算法
不会就选b44 分钟前
算法日常・每日刷题--<贪心+大根堆>2
数据结构·算法
码艺-Alimjan1 小时前
维吾尔语数字转文本
java·javascript·python·算法·go
AI服务老曹1 小时前
算法任务配置完整流程:明厨亮灶项目从0到1怎么做 | AI视频分析算法实践
人工智能·算法·音视频