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;
}
相关推荐
QXH2000002 分钟前
数据结构—双向链表
c语言·数据结构·算法·链表
旺小仔.21 分钟前
【数据结构篇】~排序(1)之插入排序
c语言·数据结构·算法·链表·性能优化·排序算法
绎岚科技1 小时前
深度学习自编码器 - 随机编码器和解码器篇
人工智能·深度学习·算法·机器学习
jingling5551 小时前
后端开发刷题 | 数字字符串转化成IP地址
java·开发语言·javascript·算法
云边有个稻草人1 小时前
【刷题】Day5--数字在升序数组中出现的次数
开发语言·笔记·算法
CV金科1 小时前
蓝桥杯-STM32G431RBT6(解决LCD与LED引脚冲突的问题)
c语言·stm32·单片机·嵌入式硬件·蓝桥杯
ymchuangke1 小时前
评价类——熵权法(Entropy Weight Method, EWM),完全客观评价
人工智能·python·算法·机器学习·数学建模
嵌入式杂谈1 小时前
人工智能在C/C++中的应用:图像处理与机器学习
c语言·c++·人工智能
Crossoads2 小时前
【数据结构】排序算法---希尔排序
c语言·开发语言·数据结构·算法·排序算法
skaiuijing2 小时前
巧用二级指针
c语言·开发语言·算法·架构·操作系统