LeetCode 824: Goat Latin Solution

Master LeetCode problem 824 (Goat Latin), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

824. Goat Latin

Easy

Problem Explanation

Explanation:

To solve this problem, we will iterate over each word in the input sentence, apply the rules of Goat Latin to each word, and construct the final Goat Latin sentence. We will follow these steps:

  1. Split the input sentence into words.
  2. For each word, determine if it starts with a vowel or a consonant.
  3. Apply the corresponding rule to convert the word to Goat Latin.
  4. Append the modified word to the result sentence along with the appropriate number of 'a's at the end based on the word index.

Time Complexity: O(n^2) where n is the length of the input sentence Space Complexity: O(n) for storing the final Goat Latin sentence

:

Solution Code

class Solution {
    public String toGoatLatin(String sentence) {
        StringBuilder result = new StringBuilder();
        String[] words = sentence.split(" ");
        Set<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
        
        for (int i = 0; i < words.length; i++) {
            StringBuilder modifiedWord = new StringBuilder();
            char firstChar = words[i].charAt(0);
            
            if (vowels.contains(firstChar)) {
                modifiedWord.append(words[i]);
            } else {
                modifiedWord.append(words[i].substring(1)).append(words[i].charAt(0));
            }
            
            modifiedWord.append("ma").append("a".repeat(i + 1));
            result.append(modifiedWord).append(" ");
        }
        
        return result.toString().trim();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 824 (Goat Latin)?

This page provides optimized solutions for LeetCode problem 824 (Goat Latin) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 824 (Goat Latin)?

The time complexity for LeetCode 824 (Goat Latin) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 824 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 824 in Java, C++, or Python.

Back to LeetCode Solutions