[LeetCode] 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’.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
string breakPalindrome(string s) {
if(s.length() == 1) {
return "";
}
bool skip = s.length() & 1;
int mid = s.length() / 2;
for(int i = 0; i < s.length(); i++) {
if(skip and mid == i) continue;
if(s[i] > 'a') {
s[i] = 'a';
return s;
}
}
s.back() = 'b';
return s;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/03/PS/LeetCode/break-a-palindrome/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.