[Leet Code] Goat Latin

Leetcode: https://leetcode.com/problems/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:

Example 2:


Explanation :

First we split the string into a list, then we create the answer variable. The vowels list will allow us to check whether a vowel is at the start or of the word or not. We enumerate through the list. This will give us the value and the index that the value is at. We check the value, v, its first letter, to check if it’s a vowel or consonant. If it’s a consonant, we take the first letter and assign it in memory to first_letter, then we shorten the value of the variable from the first index, to the second, taking away the first letter, and then we add on the first_letter variable so that it’s at the end of the word. Then we carry on as if it was a vowel, as both have the same procedure from here on. We add “ma” to the end of the word, and then we add the amount of ‘a’s to the value of the index + 1 (as the index will start at 0). Lastly, we add the list item to the answer string, then finally, we return the string with the strip method as this will take away the whitespace at the end.



Learning, and posting my findings!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store