【LeetCode---Algorithm Brushing Questions】Goat Latin (Question Number: 824)

1. Problem description

You are given a sentence sentence consisting of several words separated by spaces. Each word consists only of uppercase and lowercase English letters.
Please convert the sentence to "Goat Latin" (a fictional language similar to Pig Latin). The rules for Goat Latin are as follows:
if a word begins with a vowel ('a', 'e', ​​'i', 'o', 'u'), add "ma" after the word.
For example, the word "apple" becomes "applema".
If the word starts with a consonant (ie, not a vowel), remove the first character and put it at the end, then add "ma".

For example, the word "goat" becomes "oatgma".
Depending on the index of the word in the sentence, add the same number of letters 'a' at the end of the word as the index, the index starts from 1.
For example, add "a" after the first word, "aa" after the second word, and so on.
Returns the sentence after converting sentence to goat latin.

2. Problem-solving ideas

Investigate the use of array and string methods
First convert the string into an array, judge the first letter of each array element and then do the corresponding processing.

3. Problem solving

/**
 * @param {string} sentence
 * @return {string}
 */
var toGoatLatin = function(sentence) {
    
    
  let sentenceArr = sentence.split(' ');
  let formatterArr =  sentenceArr.map((item, index) => {
    
    
    let firstLetter = item.slice(0, 1);
    if(firstLetter === 'a' || firstLetter === 'A' || firstLetter === 'e'
    || firstLetter === 'E' || firstLetter === 'i' || firstLetter === 'I'
    || firstLetter === 'o' || firstLetter === 'O' || firstLetter === 'u'
    || firstLetter === 'U') {
    
    
      item = item + 'ma' + 'a'.repeat(index + 1);
    } else {
    
    
      item = item.slice(1) + firstLetter + 'ma' + 'a'.repeat(index + 1);
    }
      return item;
    })
  return formatterArr.join(' ');
};

(1) output:
insert image description here
insert image description here

Problem source: LeetCode
link: https://leetcode-cn.com/problems/goat-latin/submissions/

Guess you like

Origin blog.csdn.net/honeymoon_/article/details/124255495