LeetCode //C - 1328. Break a Palindrome

1328. Break a Palindrome

Given a palindromic string of lowercase English letters palindrome, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible.

Return the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string.

A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, a has a character strictly smaller than the corresponding character in b. For example, "abcc" is lexicographically smaller than "abcd" because the first position they differ is at the fourth character, and 'c' is smaller than 'd'.

Example 1:

Input: palindrome = "abccba"

Output: "aaccba"

Explanation: There are many ways to make "abccba" not a palindrome, such as "zbccba", "aaccba", and "abacba".

Of all the ways, "aaccba" is the lexicographically smallest.

Example 2:

Input: palindrome = "a"

Output: ""

Explanation: There is no way to replace a single character to make "a" not a palindrome, so return an empty string.

Constraints:
  • 1 <= palindrome.length <= 1000
  • palindrome consists of only lowercase English letters.

From: LeetCode

Link: 1328. Break a Palindrome


Solution:

Ideas:

The idea is to make the string lexicographically smallest by turning the leftmost possible character into 'a' (only scanning the first half, since changing the middle of an odd-length palindrome doesn't break the palindrome). If all characters in the first half are already 'a', you can't make it smaller without keeping it a palindrome, so you change the very last character to 'b' instead. If the string length is 1, no change is possible.

Code:
c 复制代码
char* breakPalindrome(char* palindrome) {
    int n = strlen(palindrome);
    
    // A single character cannot be changed to a non‑palindrome
    if (n == 1) return "";
    
    // Try to change the earliest possible character to 'a'
    // Only scan the first half (excluding the middle for odd lengths)
    for (int i = 0; i < n / 2; i++) {
        if (palindrome[i] != 'a') {
            palindrome[i] = 'a';
            return palindrome;
        }
    }
    
    // If we reach here, all characters in the first half are 'a'.
    // Changing the last character to 'b' gives the lexicographically smallest result.
    palindrome[n - 1] = 'b';
    return palindrome;
}
相关推荐
电科_银尘17 分钟前
【大模型算法与工程 46】vLLM部署入门:模型服务、请求与运行观测
算法·vllm
AskHarries1 小时前
社区运营打法
算法
人间乄惊鸿客17 小时前
c++ 右值
c++·算法
fanstuck18 小时前
AI 客服答错了,三分钟分清是 Prompt 还是系统的锅
算法
田里的水稻19 小时前
FA_编程算法200个分类列数-SUM
算法·分类·数据挖掘
瑶池酒剑仙20 小时前
C++重构与代码质量完全指南:从设计模式、SOLID原则到代码审查与静态分析的工程实践(所赖君子见机)
c语言·开发语言·c++·设计模式·重构·哈希算法·visual studio
猿人谷21 小时前
从百万个 Pareto 解中选出 100 个:Riesz s-Energy 如何实现高效的多样性选择?
后端·算法·aigc
地平线开发者21 小时前
地平线 × 同济无人车队:PointPillars 从浮点模型到 BPU 部署
算法·自动驾驶