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;
}
相关推荐
alphaTao1 小时前
LeetCode 每日一题 2025/12/15-2025/12/21
算法·leetcode
写写闲篇儿4 小时前
下一个更大元素(一)
数据结构·算法
MobotStone5 小时前
从金鱼记忆到过目不忘:Transformer 如何让AI真正理解一句话?
算法
炽烈小老头6 小时前
【每天学习一点算法 2025/12/19】二叉树的层序遍历
数据结构·学习·算法
Xの哲學7 小时前
Linux grep命令:文本搜索的艺术与科学
linux·服务器·算法·架构·边缘计算
soft20015257 小时前
MySQL Buffer Pool深度解析:LRU算法的完美与缺陷
数据库·mysql·算法
superman超哥7 小时前
仓颉语言中锁的实现机制深度剖析与并发实践
c语言·开发语言·c++·python·仓颉
夜月yeyue7 小时前
Linux 调度类(sched_class)
linux·运维·c语言·单片机·性能优化
WBluuue7 小时前
AtCoder Beginner Contest 436(ABCDEF)
c++·算法
fie88897 小时前
广义 S 变换(GST)地震信号时频谱
算法