LeetCode Solutions

824. Goat Latin

Time: $O(|\texttt{S}|)$

Space: $O(|\texttt{S}|)$

			

class Solution {
 public:
  string toGoatLatin(string S) {
    string ans;
    const unordered_set<char> vowels{'a', 'e', 'i', 'o', 'u',
                                     'A', 'E', 'I', 'O', 'U'};
    istringstream iss(S);
    string word;
    int i = 1;

    while (iss >> word) {
      if (i > 1)
        ans += ' ';
      if (vowels.count(word[0]))
        ans += word;
      else
        ans += word.substr(1) + word[0];
      ans += "ma" + string(i++, 'a');
    }

    return ans;
  }
};
			

class Solution {
  public String toGoatLatin(String S) {
    String ans = "";
    final String vowels = "aeiouAEIOU";
    final String[] words = S.split(" ");
    int i = 1;

    for (final String word : words) {
      if (i > 1)
        ans += " ";
      if (vowels.contains("" + word.charAt(0)))
        ans += word;
      else
        ans += word.substring(1) + word.charAt(0);
      ans += "ma"
             + "a".repeat(i++);
    }

    return ans;
  }
}
			

class Solution:
  def toGoatLatin(self, S: str) -> str:
    ans = ''
    vowels = 'aeiouAEIOU'
    words = S.split()
    i = 1

    for word in words:
      if i > 1:
        ans += ' '
      if word[0] in vowels:
        ans += word
      else:
        ans += word[1:] + word[0]
      ans += 'ma' + 'a' * i
      i += 1

    return ans