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;
}
相关推荐
Psycho_MrZhang13 分钟前
模型量化和剪枝
人工智能·算法·剪枝
梭七y19 分钟前
【力扣hot100题】(075)数据流的中位数
算法·leetcode·职场和发展
梭七y22 分钟前
【力扣hot100题】(073)数组中的第K个最大元素
算法·leetcode·职场和发展
青椒大仙KI1124 分钟前
25/4/9 算法笔记 DBGAN+强化学习+迁移学习实现青光眼图像去模糊1
人工智能·笔记·学习·算法·迁移学习
weixin_4284984929 分钟前
Fortran 中读取 MATLAB 生成的数据文件
算法
整点薯条吃吃喽1 小时前
C,C++,C#
c语言·c++·c#
Joe_Wang51 小时前
[leetcode]1786. 从第一个节点出发到最后一个节点的受限路径数(Dijkstra+记忆化搜索/dp)
算法·leetcode·图论
spssau1 小时前
论文评价指标体系构建,AHP-熵值法组合赋权,11种权重计算方法汇总
人工智能·算法·机器学习
jz_ddk1 小时前
[实战] linux驱动框架与驱动开发实战
linux·运维·c语言·驱动开发·嵌入式硬件
什么半岛铁盒2 小时前
Linux动态库 vs 静态库:创建步骤与优缺点对比
linux·c语言·c++