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 分钟前
【期货量化入门】期权交易入门:从零开始学期权量化(TqSdk完整教程)
数据库·python·mysql·算法·区块链·程序员创富
期货资管源码9 分钟前
期货资管分仓软件开发/平台搭建经验分享
经验分享·算法·eclipse·区块链
HUST9 分钟前
C语言第十一讲: 深入理解指针(1)
c语言·开发语言
Xの哲學23 分钟前
Linux 实时调度机制深度解析
linux·服务器·网络·算法·边缘计算
fie888925 分钟前
基于蚁群算法求解带时间窗的车辆路径问题
数据库·人工智能·算法
ytttr87331 分钟前
基于人工蜂群算法(ABC)的MATLAB数值计算求解框架
开发语言·算法·matlab
珂朵莉MM36 分钟前
2025年睿抗机器人开发者大赛CAIP-编程技能赛-高职组(国赛)解题报告 | 珂学家
java·开发语言·人工智能·算法·机器人
这周也會开心43 分钟前
JVM-垃圾回收器
jvm·算法
橘颂TA43 分钟前
【剑斩OFFER】算法的暴力美学——力扣 844 题:比较含退格的字符串
数据结构·c++·算法·力扣·结构与算法
cici158741 小时前
基于正交匹配追踪(OMP)算法的信号稀疏分解MATLAB实现
数据库·算法·matlab