20 August 2020
LeetCode(1328) -- Break a Palindrome
by Jerry Zhang
Problem
Given a palindromic string palindrome, replace exactly one character by any lowercase English letter so that the string becomes the lexicographically smallest possible string that isn’t a palindrome.
After doing so, return the final string. If there is no way to do so, return the empty string.
Example 1:
Input: palindrome = "abccba"
Output: "aaccba"
My Solution
class Solution {
public String breakPalindrome(String palindrome) {
if (palindrome.length() <= 1) {
return "";
}
char[] chars = palindrome.toCharArray();
for (int i = 0; i < palindrome.length() / 2; i++) {
if (chars[i] != 'a') {
chars[i] = 'a';
return new String(chars);
}
}
chars[palindrome.length() - 1] = 'b';
return new String(chars);
}
}