[leetcode #1328] Break a Palindrome

Seongyeol Shin·2021년 9월 24일
0

leetcode

목록 보기
31/196
post-thumbnail

Problem

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.

Example 3:

Input: palindrome = "aa"
Output: "ab"

Example 4:

Input: palindrome = "aba"
Output: "abb"

Constraints:

1 <= palindrome.length <= 1000
palindrome consists of only lowercase English letters.

Idea

Palindrome인 string을 단 하나의 문자만 바꿔서 palindrome이 아닌 문자로 변형하는 문제다. 아무 문자나 바꾸면 쉽겠지만, 변형 가능한 문자열 중 오름차순으로 정렬했을 때 가장 앞에 오는 문자열을 리턴해야 한다는 제한이 있다.

사전순으로 정렬했을 때 가장 앞에 오는 문자열을 만들기 위해서는 'a'가 아닌 문자를 'a'로 바꾸면 된다. 문자열의 모든 문자가 'a'일 경우 가장 마지막 문자를 'b'로 바꾸면 된다. 문자열의 길이가 1일 때는 문자를 바꿔도 palindrome이 되므로 빈 문자열을 리턴한다.

알고리즘은 다음과 같다. (Greedy)

  1. 문자열의 길이가 1일 경우 빈 문자열을 리턴한다.
  2. 문자열을 탐색하며 'a'가 아닌 문자를 찾아 'a'로 바꾼 뒤 리턴한다.
  3. 모든 문자가 'a'일 경우 가장 마지막 문자를 'b'로 바꿔 리턴한다.

Solution

class Solution {
    public String breakPalindrome(String palindrome) {
    	int len = palindrome.length();
        boolean isEven = len % 2 == 0;

        if (len == 1)
            return "";

        StringBuilder stringBuilder = new StringBuilder(palindrome);
        int replaceIndex = findNotA(palindrome);
        if (palindrome.charAt(replaceIndex) != 'a')
            stringBuilder.setCharAt(replaceIndex, 'a');
        else
            stringBuilder.setCharAt(replaceIndex, 'b');

        return stringBuilder.toString();
    }

    private int findNotA(String str) {
        int len = str.length() / 2 - 1;
        for (int i = 0; i <= len; i++) {
            if (str.charAt(i) != 'a')
                return i;
        }
        return str.length()-1;
    }
}

Reference

https://leetcode.com/problems/break-a-palindrome/

profile
서버개발자 토모입니다

0개의 댓글