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;
}
相关推荐
载数而行52013 分钟前
算法系列2之最短路径
c语言·数据结构·c++·算法·贪心算法
代码改善世界1 小时前
栈和队列的实现与详解(C语言版):从底层原理到代码实战
c语言·开发语言
逆境不可逃1 小时前
【除夕篇】LeetCode 热题 100 之 189.轮转数组
java·数据结构·算法·链表
xiaoye-duck1 小时前
《算法题讲解指南:优选算法-滑动窗口》--13 水果成篮
c++·算法
wefg11 小时前
【算法】模运算的技巧
算法
智者知已应修善业1 小时前
【冰雹猜想过程逆序输出】2025-4-19
c语言·c++·经验分享·笔记·算法
编程小白_澄映1 小时前
机器学习——特征工程
人工智能·算法·机器学习
美好的事情能不能发生在我身上1 小时前
Leetcode热题100中的:哈希专题
算法·leetcode·哈希算法
wefg12 小时前
【算法】倍增思想(快速幂)
数据结构·c++·算法
Zik----2 小时前
Leetcode24 —— 两两交换链表中的节点(迭代法)
数据结构·算法·链表