一、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"
Example 2
Input: palindrome = "a"
Output: ""
二、Solution
方法一:思維題
- 找到第一個非
'a'
字符,將其提換成'b'
;如果找不到,則證明字符串全是'a'
,於是將最後一個字符替換成'b'
,可滿足替換後的字符串字典序最小。 - 給定的字符串是迴文的,所以只需要枚舉 [0, n/2]
class Solution {
public String breakPalindrome(String palindrome ) {
char[] s = palindrome.toCharArray();
int n = s.length;
if (n == 1)
return "";
for (int i = 0; i < n/2; i++) {
if (s[i] != 'a') {
s[i] = 'a';
return new String(s);
}
}
s[n-1] = 'b';
return new String(s);
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,