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;
}
相关推荐
superman超哥17 分钟前
仓颉锁竞争优化深度解析
c语言·开发语言·c++·python·仓颉
业精于勤的牙26 分钟前
最长特殊序列(二)
java·开发语言·算法
yong999037 分钟前
C#实现OPC客户端与S7-1200 PLC的通信
开发语言·网络·算法·c#
yaoh.wang43 分钟前
力扣(LeetCode) 111: 二叉树的最小深度 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·深度优先
qq_401700411 小时前
const 指针:内存安全锁
c语言
啊阿狸不会拉杆1 小时前
《数字图像处理》第 11 章 - 特征提取
图像处理·人工智能·算法·计算机视觉·数字图像处理
那雨倾城1 小时前
PiscCode实现用 YOLO 给现实世界加上「NPC 血条 HUD」
图像处理·python·算法·yolo·计算机视觉·目标跟踪
夏幻灵1 小时前
C++ 中手动重载赋值运算符(operator=)时实现部分复制的思路和方法
开发语言·c++·算法
九河云1 小时前
人工智能驱动企业数字化转型:从效率工具到战略引擎
人工智能·物联网·算法·机器学习·数字化转型
superman超哥1 小时前
仓颉语言中包与模块系统的深度剖析与工程实践
c语言·开发语言·c++·python·仓颉