Given a palindromic string of lowercase English letters palindrome
, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible.
Return the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string.
A string a
is lexicographically smaller than a string b
(of the same length) if in the first position where a
and b
differ, a
has a character strictly smaller than the corresponding character in b
. For example, "abcc"
is lexicographically smaller than "abcd"
because the first position they differ is at the fourth character, and 'c'
is smaller than 'd'
.
Example 1:
Input: palindrome = "abccba" Output: "aaccba" Explanation: There are many ways to make "abccba" not a palindrome, such as "zbccba", "aaccba", and "abacba". Of all the ways, "aaccba" is the lexicographically smallest.
Example 2:
Input: palindrome = "a" Output: "" Explanation: There is no way to replace a single character to make "a" not a palindrome, so return an empty string.
Constraints:
1 <= palindrome.length <= 1000
palindrome
consists of only lowercase English letters.
破坏回文串。
给你一个由小写英文字母组成的回文字符串 palindrome ,请你将其中 一个 字符用任意小写英文字母替换,使得结果字符串的 字典序最小 ,且 不是 回文串。
请你返回结果字符串。如果无法做到,则返回一个 空串 。
如果两个字符串长度相同,那么字符串 a 字典序比字符串 b 小可以这样定义:在 a 和 b 出现不同的第一个位置上,字符串 a 中的字符严格小于 b 中的对应字符。例如,"abcc” 字典序比 "abcd" 小,因为不同的第一个位置是在第四个字符,显然 'c' 比 'd' 小。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/break-a-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目的 input 给的是一个合法的回文串,我们要做的是修改其中的一个字母,从而使得修改过后的字符串不是回文串同时字典序最小。
我们回顾回文串的定义,发现回文串只有两种情况,一种是 abba,一种是 aba。同时既然需要做到修改之后字典序最小,那么我们只看字符串的左半边就好了,看右半边是无法做到修改后的结果是字典序最小的。这道题我们需要注意两个 corner case,一个是如果input中字母都是a,类似 aaaaaaa 的话,那么我们只能通过把最后一个 a 改成 b 来保证修改结果字典序最小。另外一个 case 是比如例子二,那么我们只能将他改成空字符串返回。
时间O(n)
空间O(n) - char array
Java实现
1 class Solution { 2 public String breakPalindrome(String palindrome) { 3 int len = palindrome.length(); 4 char[] word = palindrome.toCharArray(); 5 for (int i = 0; i < len / 2; i++) { 6 if (word[i] != 'a') { 7 word[i] = 'a'; 8 return String.valueOf(word); 9 } 10 } 11 word[len - 1] = 'b'; 12 if (len < 2) { 13 return ""; 14 } 15 return String.valueOf(word); 16 } 17 }
标签:palindrome,word,string,1328,character,Break,Palindrome,字符串,回文 From: https://www.cnblogs.com/cnoodle/p/16777967.html