
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)
1public class Solution {
2 public string BreakPalindrome(string palindrome) {
3 int len = palindrome.Length;
4 if (len == 1) return "";
5 char[] chars = palindrome.ToCharArray();
6
7 for (int i = 0; i < len / 2; ++i) {
8 if (chars[i] != 'a') {
9 chars[i] = 'a';
10 return new string(chars);
11 }
12 }
13 chars[len - 1] = 'b';
14 return new string(chars);
15 }
16}The C# solution uses a character array for easy manipulation, trying to change the first non-'a' or the last character if necessary.
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)
1def
The Python solution prioritizes the center character for modification in odd-length cases, effectively breaking the symmetry.