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;
}
相关推荐
wanderist.12 小时前
算法模板-字符串
数据结构·算法·哈希算法
xiaoye-duck12 小时前
《算法题讲解指南:动态规划算法--子序列问题》--29.最长递增子序列的个数,30.最长数对链,31.最长定差子序列
c++·算法·动态规划
Yzzz-F12 小时前
Problem - 2180D - Codeforces
算法
moonsea020312 小时前
2023.9.25
算法
汀、人工智能12 小时前
[特殊字符] Python基础语法速成教程
算法·链表·均值算法·哈希表·lru缓存·python基础语法速成教程
tankeven12 小时前
HJ164 太阳系DISCO
c++·算法
来自远方的老作者12 小时前
第7章 运算符-7.1 算术运算符
开发语言·数据结构·python·算法·算术运算符
white-persist13 小时前
【vulhub weblogic CVE-2017-10271漏洞复现】vulhub weblogic CVE-2017-10271漏洞复现详细解析
java·运维·服务器·网络·数据库·算法·安全
不爱吃炸鸡柳13 小时前
[特殊字符]C/C++内存管理深度解剖:从内存布局到new/delete底层,吃透面试必考核心
c语言·c++·面试
汀、人工智能13 小时前
[特殊字符] 第9课:三数之和
数据结构·算法·数据库架构·图论·bfs·三数之和