Goat Latin LeetCode Solution - The Coding Shala

Home >> LeetCode >> Goat Latin

 In this post, we will learn how to solve LeetCode's Goat Latin problem and will implement its solution in Java.

Goat Latin Problem

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"

LeetCode - Goat Latin Java Solution

Approach 1

Using loop.

Time Complexity: O(n)

Java Program: 

class Solution {
    public String toGoatLatin(String S) {
        StringBuilder res = new StringBuilder();
        String[] arr = S.split(" ");
        String aStr = "maa";
        for(int i = 0; i < arr.length; i++) {
            char ch = arr[i].charAt(0);
            if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
               ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
                res.append(arr[i] + aStr + " ");
            } else {
                res.append(arr[i].substring(1) + arr[i].charAt(0) + aStr + " ");
            }
            aStr += "a";
        }
        return res.toString().trim();
    }
}

We can also make a HashSet of vowels and then check with contains method.

Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala