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;
}
相关推荐
GalaxyPokemon44 分钟前
归并排序:分治思想的高效排序
数据结构·算法·排序算法
ThreeYear_s1 小时前
基于FPGA的PID算法学习———实现PI比例控制算法
学习·算法·fpga开发
我不是加奈3 小时前
QMC5883L的驱动
c语言·驱动开发·单片机·嵌入式硬件
Coding小公仔3 小时前
LeetCode 240 搜索二维矩阵 II
算法·leetcode·矩阵
C++chaofan3 小时前
74. 搜索二维矩阵
java·算法·leetcode·矩阵
青小莫4 小时前
数据结构-C语言-链表OJ
c语言·数据结构·链表
Studying 开龙wu4 小时前
机器学习监督学习实战五:六种算法对声呐回波信号进行分类
学习·算法·机器学习
Mi Manchi264 小时前
力扣热题100之二叉树的层序遍历
python·算法·leetcode
wu~9704 小时前
leetcode:42. 接雨水(秒变简单题)
算法·leetcode·职场和发展