Break a Palindrome

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"

Example 2:

Input: palindrome = "a"
Output: ""

 

Constraints:


Solution:

class Solution {
    public String breakPalindrome(String palindrome) {
        if (palindrome.length() == 1) return "";
        StringBuilder sb = new StringBuilder(palindrome);
        int mid = -1;
        if (sb.length() % 2 == 1) {
            mid = sb.length() / 2;
        }
        for (int i = 0; i < sb.length(); i ++) {
            if (sb.charAt(i) != 'a' && i != mid) {
                sb.setCharAt(i, 'a');
                return sb.toString();
            }
        }
        sb.setCharAt(sb.length() - 1, 'b');
        return sb.toString();
    }
}