LeetCode //C - 214. Shortest Palindrome

214. Shortest Palindrome

You are given a string s. You can convert s to a palindrome by adding characters in front of it.

Return the shortest palindrome you can find by performing this transformation.

Example 1:

Input: s = "aacecaaa"
Output: "aaacecaaa".

Example 2:

Input: s = "abcd"
Output: "dcbabcd"

Constraints:
  • 0 < = s . l e n g t h < = 5 ∗ 1 0 4 0 <= s.length <= 5 * 10^4 0<=s.length<=5∗104
  • s consists of lowercase English letters only.

From: LeetCode

Link: 214. Shortest Palindrome


Solution:

Ideas:
  1. Reverse the input string: This will help us find the longest palindromic prefix.
  2. Find the longest palindromic prefix: By comparing the original string with the suffixes of the reversed string, we determine the longest prefix of the original string that is also a suffix of the reversed string.
  3. Form the result string: Add the necessary characters (the part of the reversed string that does not match the prefix) in front of the original string to make it a palindrome.
Code:
c 复制代码
void reverseString(char* str) {
    int n = strlen(str);
    for (int i = 0; i < n / 2; i++) {
        char temp = str[i];
        str[i] = str[n - i - 1];
        str[n - i - 1] = temp;
    }
}

char* shortestPalindrome(char* s) {
    int n = strlen(s);
    if (n == 0) return "";

    // Create the reversed string
    char* rev_s = (char*)malloc((n + 1) * sizeof(char));
    strcpy(rev_s, s);
    reverseString(rev_s);

    // Find the longest palindromic prefix
    int i;
    for (i = n; i >= 0; i--) {
        if (strncmp(s, rev_s + n - i, i) == 0) {
            break;
        }
    }

    // Build the shortest palindrome by adding the necessary characters in front of s
    char* result = (char*)malloc((2 * n - i + 1) * sizeof(char));
    strcpy(result, rev_s);
    strncat(result, s + i, n - i);

    // Free allocated memory
    free(rev_s);

    return result;
}
相关推荐
小李独爱秋1 小时前
模拟面试:什么是微服务架构,它的优缺点是什么?
算法·微服务·面试·职场和发展·框架·架构师
流云鹤1 小时前
2026牛客寒假算法基础集训营3(A B G J H F C)
算法
御坂10101号1 小时前
从暴力扫图到成本估算:SpiceDB 如何重构 ReBAC 性能引擎
算法·性能优化·架构·database
小程故事多_801 小时前
RAG,基于字号频率的内容切分算法,非常强
人工智能·算法·aigc
ADDDDDD_Trouvaille1 小时前
2026.2.15——OJ83-85题
c++·算法
烟花落o2 小时前
算法的时间复杂度和空间复杂度
开发语言·数据结构·笔记·算法
蒟蒻小袁2 小时前
力扣hot-100(一刷自用版)
leetcode·哈希算法·散列表
Ronaldinho Gaúch2 小时前
算法题中的日期问题
开发语言·c++·算法
踩坑记录2 小时前
leetcode ho100 124. 二叉树中的最大路径和 hard
leetcode
Chary20162 小时前
Opencascade VTK 集成服务 VIS
算法