码迷,mamicode.com
首页 > 其他好文 > 详细

1328. Break a Palindrome

时间:2020-01-30 09:47:14      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:replace   ase   第一个   bsp   col   char   rom   替换   else   

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

标签:replace   ase   第一个   bsp   col   char   rom   替换   else   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!