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;
}
相关推荐
whoarethenext5 分钟前
使用 C/C++、OpenCV 和 Libevent 构建联网人脸识别考勤系统 [特殊字符]‍[特殊字符]
c语言·c++·opencv
焜昱错眩..36 分钟前
代码随想录训练营二十六天| 654.最大二叉树 617.合并二叉树 700.二叉搜索树的搜索 98.验证二叉搜索树
数据结构·算法
jndingxin43 分钟前
OpenCV CUDA模块中用于稠密光流计算的 TV-L1(Dual TV-L1)算法类cv::cuda::OpticalFlowDual_TVL1
人工智能·opencv·算法
geneculture1 小时前
路径=算法=操作:复杂系统行为的统一数学框架
人工智能·算法·数学建模·课程设计·智慧系统·融智学的重要应用·复杂系统
AcrelGHP1 小时前
建筑末端配电回路安全用电解决方案:筑牢电气防火最后一道防线
人工智能·算法·安全
Watink Cpper1 小时前
[灵感源于算法] 链表类问题技巧总结
数据结构·算法·链表
PassLink_3 小时前
AlgorithmVisualizer项目改进与部署-网页算法可视化
算法·编程·开源项目·本地部署·算法可视化·源码改进
GalaxyPokemon4 小时前
LeetCode - 2. 两数相加
java·前端·javascript·算法·leetcode·职场和发展
编程绿豆侠4 小时前
力扣HOT100之堆:347. 前 K 个高频元素
算法·leetcode·哈希算法
GalaxyPokemon6 小时前
归并排序:分治思想的高效排序
数据结构·算法·排序算法