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;
}
相关推荐
秋深枫叶红2 分钟前
嵌入式第二十九篇——数据结构——树
数据结构·学习·算法·深度优先
能源系统预测和优化研究4 分钟前
【原创代码改进】基于贝叶斯优化的PatchTST综合能源负荷多变量时间序列预测
算法·回归·transformer·能源
渡我白衣5 分钟前
计算机组成原理(3):计算机软件
java·c语言·开发语言·jvm·c++·人工智能·python
小龙报8 分钟前
【C语言初阶】动态内存分配实战指南:C 语言 4 大函数使用 + 经典笔试题 + 柔性数组优势与内存区域
android·c语言·开发语言·数据结构·c++·算法·visual studio
小龙报12 分钟前
【算法通关指南:算法基础篇(三)】一维差分专题:1.【模板】差分 2.海底高铁
android·c语言·数据结构·c++·算法·leetcode·visual studio
小白程序员成长日记17 分钟前
2025.12.07 力扣每日一题
算法·leetcode·职场和发展
不悔哥18 分钟前
路由器特性——网络状态检测
linux·c语言·网络·tcp/ip·智能路由器
小李小李快乐不已26 分钟前
图论理论基础(5)
数据结构·c++·算法·机器学习·动态规划·图论
承渊政道28 分钟前
C++学习之旅【C++基础知识介绍】
c语言·c++·学习·程序人生
民乐团扒谱机29 分钟前
【微实验】大规模网络的社区检测Clauset–Newman–Moore聚类算法(附完整MATLAB代码)
算法·matlab·聚类·聚类算法·cnm·语义