首页 > 其他 > 详细

1328. Break a Palindrome

时间:2020-01-30 09:12:10      阅读:83      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/wentiliangkaihua/p/12242015.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!