LeetCode 824

Goat Latin

문제 출처

문제

A sentence S is given, composed 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 S to Goat Latin.



Example 1:

Input: "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
Example 2:

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


Notes:

S contains only uppercase, lowercase and spaces. Exactly one space between each word.
1 <= S.length <= 150.

나의 코드 1

/**
 * @param {string} S
 * @return {string}
 */
var toGoatLatin = function (S) {
  const vowels = {
    a: true,
    A: true,
    e: true,
    E: true,
    i: true,
    I: true,
    o: true,
    O: true,
    u: true,
    U: true,
  };
  const words = S.split(" ");

  return words
    .map((c, i) => {
      let converted = c;
      if (!vowels[c[0]]) {
        converted = beginWithConsonant(c);
      }
      return `${converted}${makeMA(i)}`;
    })
    .join(" ");
};

function beginWithConsonant(word) {
  const letters = word.split("");
  letters.push(letters[0]);
  return letters.slice(1).join("");
}

function makeMA(index) {
  const a = new Array(index + 1);
  return `ma${a.fill("a").join("")}`;
}

참고 코드

+ 연산으로 문자열을 합쳤다.

/**
 * @param {string} S
 * @return {string}
 */
var toGoatLatin = function (S) {
  const vowels = new Set(["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]);
  return S.split(" ")
    .map((w, i) =>
      vowels.has(w[0])
        ? w + "ma" + "a".repeat(i + 1)
        : w.slice(1) + w[0] + "ma" + "a".repeat(i + 1)
    )
    .join(" ");
};

배운점

  • String.prototype.repeat() 을 잊고 있었는데 다시 알게됨 (링크)

  • 문자열 + 연산이 효율적이지 않다는 글을 읽은 적이 있는데 Test 해보니 확실히 template literal 로 합친 내 코드보다 효율적이지 않았다.