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;
}
相关推荐
折哥的程序人生 · 物流技术专研7 小时前
Java面试85题图解版 · 特别篇:2026后端高频面试题复盘(算法底层逻辑+高并发架构设计全解析,附Java实战代码)
java·网络·数据库·算法·面试
玖玥拾8 小时前
C/C++ 基础笔记(十四)多态与模板编程
c语言·c++·多态·模板
想吃火锅10058 小时前
【leetcode】14.最长公共前缀js
算法·leetcode·职场和发展
云絮.9 小时前
数据库操作
数据库·mysql·算法·oracle
小林ixn9 小时前
LeetCode 206. 反转链表(迭代 + 递归详解)
算法·leetcode·链表
凡人叶枫10 小时前
Effective C++ 条款17:以独立语句将 newed 对象置入智能指针
java·linux·开发语言·c++·算法
菜鸟‍11 小时前
LeetCode 1 27 和 704 || 两数之和 移除元素 二分查找
算法·leetcode·职场和发展
caimouse12 小时前
Reactos 第1章 概述
c语言·开发语言·架构
退休倒计时12 小时前
【每日一题】LeetCode 142. 环形链表 II TypeScript
算法·leetcode·链表·typescript
啊森要自信12 小时前
【GUI自动化测试】控件、鼠标键盘操作与多场景自动化
c语言·开发语言·python·adb·ipython