1.문제
You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows:
- If a word begins with a vowel ('a', 'e', 'i', 'o', or 'u'), append "ma" to the end of the word.
- For example, the word "apple" becomes "applema".
- If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add "ma".
- For example, the word "goat" becomes "oatgma".
- Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1.
- For example, the first word gets "a" added to the end, the second word gets "aa" added to the end, and so on.
Return the final sentence representing the conversion from sentence to Goat Latin.
문자열 sentence 가 주어질 때 문자열의 단어들을 아래의 규칙대로 바꾼 문자열을 리턴하는 문제이다.
- 단어가 모음으로 시작하면 단어 뒤에 'ma'를 붙인다.
- 단어가 자음으로 시작하면 맨처음 알파벳을 단어 맨 뒤로 옮기고 'ma'를 붙인다.
- 단어의 index(1부터 시작)에 따라 'a' * i 만큼을 단어 뒤에 추가로 붙인다.
Example 1
Input: sentence = "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
Example 2
Input: sentence = "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
Constraints:
- 1 <= sentence.length <= 150
- sentence consists of English letters and spaces.
- sentence has no leading or trailing spaces.
- All the words in sentence are separated by a single space.
2.풀이
- sentence를 공백기준으로 잘라서 배열로 만든다.
- 배열을 for문을 돌면서 각 단어들을 체크해서 처리를 해준다.
/**
* @param {string} sentence
* @return {string}
*/
const toGoatLatin = function (sentence) {
sentence = sentence.split(" ");
for (let i = 0; i < sentence.length; i++) {
if (
sentence[i][0] === "a" ||
sentence[i][0] === "e" ||
sentence[i][0] === "i" ||
sentence[i][0] === "o" ||
sentence[i][0] === "u" ||
sentence[i][0] === "A" ||
sentence[i][0] === "E" ||
sentence[i][0] === "I" ||
sentence[i][0] === "O" ||
sentence[i][0] === "U"
) {
// 모음으로 시작하면 단어 뒤에 'ma' 더하기
sentence[i] = sentence[i] + "ma";
} else {
// 모음으로 시작하지 않으면 제일 앞 철자를 뒤에 붙이고 'ma' 붙이기
sentence[i] = sentence[i].slice(1) + sentence[i][0] + "ma";
}
sentence[i] = sentence[i] + "a".repeat(i + 1); // 단어의 앞에서부터 순번에 따라 a 붙여준다.
}
return sentence.join(" ");
};
3.결과
