
Sponsored
Sponsored
In this approach, we iterate through the first half of the string and try to replace the first non-'a' character with 'a'. This ensures that we're making the lexicographically smallest change as early as possible in the string. If we can't find a character that is not 'a' in the first half, we replace the last character with 'b' to ensure it's not a palindrome.
Time Complexity: O(n)
Space Complexity: O(1)
1#include <string>
2
3std::string breakPalindrome(std::string palindrome) {
4 int len = palindrome.length();
5 if (len == 1) return "";
6
7 for (int i = 0; i < len / 2; ++i) {
8 if (palindrome[i] != 'a') {
9 palindrome[i] = 'a';
10 return palindrome;
11 }
12 }
13
14 palindrome[len - 1] = 'b';
15 return palindrome;
16}The C++ solution follows the same logic as the C solution, iterating through the first half to change the first non-'a' character or the end character to break the palindrome.
This approach focuses on changing the center character if possible, because altering the center in an odd-length palindrome often results in a non-palindrome quickly. For even lengths, alterations must be controlled to preserve lexicographical order.
Time Complexity: O(n)
Space Complexity: O(1)
1public class Solution {
public string BreakPalindrome(string palindrome) {
int len = palindrome.Length;
if (len == 1) return "";
char[] chars = palindrome.ToCharArray();
int mid = len / 2;
if (len % 2 == 1 && chars[mid] != 'a') {
chars[mid] = 'a';
return new string(chars);
}
for (int i = 0; i < len; ++i) {
if (chars[i] != 'a') {
chars[i] = 'a';
return new string(chars);
}
}
chars[len - 1] = 'b';
return new string(chars);
}
}C# relies on a simple mid-point check for odd-length strings, altering as needed.