LeetCode 824: Goat Latin

String

Problem Description

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

:

Solutions

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();
    }
}

Loading editor...