[
string
simulation
]
Leetcode 0824. Goat Latin
https://leetcode.com/problems/goat-latin
This is easy prolem, where you need just to do what is asked, without really thinking.
- Split our sentence into words, using
.split()
. If it is not allowed we can just traverse it and find spaces. - For every word check if it starts with vowel, if it is, add
ma
andi+1
lettersa
to the end. It isi+1
, because we start from zero index. - If first letter is not vowel, remove first letter and add it to the end, also add
ma
and lettersa
.
Complexity: time and space complexity is O(n) + O(k^2)
, where n
is number of symbols in our string and k
is number of words: do not forget about letters a
in the end: we add 1 + 2 + ... + k = O(k^2)
letters in the end.
class Solution:
def toGoatLatin(self, S):
words = S.split()
vowels = set("AEIOUaeiou")
for i in range(len(words)):
if words[i][0] in vowels:
words[i] = words[i] + "ma" + "a"*(i+1)
else:
words[i] = words[i][1:] + words[i][0] + "ma" + "a"*(i+1)
return " ".join(words)
If you like the solution, you can upvote it on leetcode discussion section: Problem 0824