[LeetCode] Goat Latin

아르당·2026년 3월 1일

LeetCode

목록 보기
177/213
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

공백으로 구분된 단어로 구성된 문자열 sentence가 주어진다. 각 단어는 소문자와 대문자로만 구성된다.

해당 문장을 "Goat Latin"("Pig Latin"과 유사한 인공 언어)로 변환하고 싶다. "Goat Latin"의 규칙은 다음과 같다.

  • 단어가 모음('a', 'e', 'i', 'o', 'u')으로 시작하면 단어 끝에 "ma"를 붙인다.
  • 예를 들어, 단어 "apple"은 "applema"가 된다.
  • 단어가 자음으로 시작하면 첫 글자를 제거하고 단어 끝에 붙이고 "ma"를 추가한다.
  • 예를 들어, 단어 "goat"는 "oatgma"가 된다.
  • 문장의 단어 인덱스(1부터 시작)에 따라 각 단어 끝에 'a'를 하나씩 추가한다.
  • 예를 들어, 첫 번째 단어 끝에 "a"가 붙고, 두 번째 단어 끝에는 "aa"가 붙는 식으로 계속된다.

문장을 Goat Latin으로 변환한 최종 문장을 반환해라.

Example

#1
Input: setence = "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"

#2
Input: setence = "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"

Constraints

  • 1 <= setence.length <= 50
  • sentence는 영문자와 공백으로 구성된다.
  • sentence는 앞뒤에 공백이 없다.
  • sentence의 모든 단어는 한 칸씩 띄어쓰기로 구분되어 있다.

Solved

class Solution {
    public String toGoatLatin(String sentence) {
        Set<Character> vowels = new HashSet<>(
            Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
        );
        String result = "";
        int i = 0;
        int j = 0;

        for(String s : sentence.split("\\s")){
            result += " " + (vowels.contains(s.charAt(0)) ? s : s.substring(1) + s.charAt(0)) + "ma";

            for(j = 0, ++i; j < i; ++j){
                result += "a";
            }
        }

        return result.substring(1);
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글