Goat Latin

easy string simulation

Problem

Convert a sentence to Goat Latin. If a word begins with a vowel, append "ma". Otherwise move the first letter to the end and add "ma". Then append "a" repeated by the 1-based word index.

Inputsentence = "I speak Goat Latin"
Output"Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
Word 1 "I" starts with a vowel -> "Imaa". Word 2 "speak" -> "peaksmaaa". And so on.

def toGoatLatin(sentence):
    vowels = set("aeiouAEIOU")
    out = []
    for i, w in enumerate(sentence.split(), 1):
        if w[0] in vowels:
            out.append(w + "ma" + "a" * i)
        else:
            out.append(w[1:] + w[0] + "ma" + "a" * i)
    return " ".join(out)
function toGoatLatin(sentence) {
  const vowels = new Set("aeiouAEIOU");
  const words = sentence.split(" ");
  return words.map((w, idx) => {
    const i = idx + 1;
    const base = vowels.has(w[0]) ? w : w.slice(1) + w[0];
    return base + "ma" + "a".repeat(i);
  }).join(" ");
}
class Solution {
  public String toGoatLatin(String sentence) {
    String vowels = "aeiouAEIOU";
    String[] words = sentence.split(" ");
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < words.length; i++) {
      String w = words[i];
      String base = vowels.indexOf(w.charAt(0)) >= 0 ? w : w.substring(1) + w.charAt(0);
      sb.append(base).append("ma");
      for (int j = 0; j <= i; j++) sb.append('a');
      if (i < words.length - 1) sb.append(' ');
    }
    return sb.toString();
  }
}
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
    string toGoatLatin(string sentence) {
        string vowels = "aeiouAEIOU";
        stringstream ss(sentence), out;
        string w;
        int i = 1;
        while (ss >> w) {
            if (vowels.find(w[0]) == string::npos) w = w.substr(1) + w[0];
            w += "ma" + string(i, 'a');
            if (i > 1) out << ' ';
            out << w;
            i++;
        }
        return out.str();
    }
};
Time: O(n) Space: O(n)