1328. Break a Palindrome
Posted wentiliangkaihua
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1328. 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:
1 <= palindrome.length <= 1000
palindrome
consists of only lowercase English letters.
class Solution { public String breakPalindrome(String palindrome) { if(palindrome.length() == 1) return ""; boolean change = false; char[] ch = palindrome.toCharArray(); for(int i = 0; i < palindrome.length()/2; i++){ if(change) break; if(ch[i] != ‘a‘){ ch[i] = ‘a‘; change = true; } } if(change){ return new String(ch); } else{ ch[palindrome.length() - 1] = ‘b‘; return new String(ch); } //return ""; } }
给定的string是palindrome,那么检查一半就可以了
本着替换第一个不是a的字符,如果全是a,那就把最后一位换成b即可。
以上是关于1328. Break a Palindrome的主要内容,如果未能解决你的问题,请参考以下文章
[虚拟机OA]Break a Palindrome 破坏回文串
优化覆盖基于matlab入侵杂草和花授粉混合算法无线传感器覆盖优化问题含Matlab源码 1328期