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;
}
相关推荐
冻柠檬飞冰走茶25 分钟前
PTA刷题集之Airline Routes(C语言实现)
c语言·开发语言·数据结构·算法
宗旨飞翔27 分钟前
不同的二叉搜索树
算法
736c39 分钟前
固件开发岗算法
数据结构·算法
青少儿编程课堂1 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:倍增法求最近公共祖先LCA解析
c++·python·算法·bfs·信息学竞赛
冻柠檬飞冰走茶1 小时前
PTA刷题集之Battle Over Cities - Hard Version(C语言实现)
c语言·开发语言·数据结构·算法
吴长建先生重名了1 小时前
电商订单系统在Docker和Kubernetes中部署的高
算法
東隅已逝,桑榆非晚3 小时前
算法2. 双指针法-复写零
c++·笔记·学习·算法
云析赢指标公式网44 小时前
文华财经指标源码笔记:WINNER筹码函数、控盘变量与MACD变体的调试记录
java·笔记·算法
CC数分5 小时前
统计学基础|先把问题问对:数据分析的六大类型
大数据·人工智能·算法
文丑颜不良啊6 小时前
LeetCode1721~1740题目解析
java·leetcode