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;
}
相关推荐
罗伯特祥23 分钟前
C调用gnuplot绘图的方法
c语言·plot
嵌入式科普1 小时前
嵌入式科普(24)从SPI和CAN通信重新理解“全双工”
c语言·stm32·can·spi·全双工·ra6m5
火星机器人life1 小时前
基于ceres优化的3d激光雷达开源算法
算法·3d
虽千万人 吾往矣2 小时前
golang LeetCode 热题 100(动态规划)-更新中
算法·leetcode·动态规划
arnold662 小时前
华为OD E卷(100分)34-转盘寿司
算法·华为od
ZZTC3 小时前
Floyd算法及其扩展应用
算法
lqqjuly3 小时前
特殊的“Undefined Reference xxx“编译错误
c语言·c++
lshzdq3 小时前
【机器人】机械臂轨迹和转矩控制对比
人工智能·算法·机器人
2401_858286114 小时前
115.【C语言】数据结构之排序(希尔排序)
c语言·开发语言·数据结构·算法·排序算法
猫猫的小茶馆4 小时前
【数据结构】数据结构整体大纲
linux·数据结构·算法·ubuntu·嵌入式软件