Skip to content

824. Goat Latin 👎

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
 public:
  string toGoatLatin(string sentence) {
    string ans;
    istringstream iss(sentence);

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

    return ans;
  }

 private:
  bool isVowel(char c) {
    static constexpr string_view kVowels = "aeiouAEIOU";
    return kVowels.find(c) != string_view::npos;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public String toGoatLatin(String sentence) {
    StringBuilder sb = new StringBuilder();

    int i = 1;
    for (final String word : sentence.split(" ")) {
      if (i > 1)
        sb.append(" ");
      if (isVowel(word.charAt(0)))
        sb.append(word);
      else
        sb.append(word.substring(1) + word.charAt(0));
      sb.append("ma").append("a".repeat(i++));
    }

    return sb.toString();
  }

  private boolean isVowel(char c) {
    return "aeiouAEIOU".indexOf(c) != -1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def toGoatLatin(self, sentence: str) -> str:
    ans = []
    kVowels = 'aeiouAEIOU'

    i = 1
    for word in sentence.split():
      if i > 1:
        ans.append(' ')
      if word[0] in kVowels:
        ans.append(word)
      else:
        ans.append(word[1:] + word[0])
      ans.append('ma' + 'a' * i)
      i += 1

    return ''.join(ans)