The 824. Goat Latin
problem requires you to transform a given sentence as per the following rules:
Given an input sentence, apply these transformations to each word and return the resultant sentence.
Yes, assume the input is always a valid sentence without leading or trailing spaces.
Yes, the words are composed of only lowercase and uppercase English letters.
No, the transformation should respect the original case of the letters.
Here’s the C++ solution to transform a sentence into “Goat Latin”:
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
class Solution {
public:
string toGoatLatin(string S) {
// Helper function to check if a character is a vowel
auto is_vowel = [](char c) -> bool {
c = tolower(c);
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
};
istringstream iss(S);
string word;
vector<string> words;
int index = 0;
while (iss >> word) {
index++;
if (is_vowel(word[0])) {
word += "ma";
} else {
word = word.substr(1) + word[0] + "ma";
}
word += string(index, 'a');
words.push_back(word);
}
string result;
for (int i = 0; i < words.size(); i++) {
if (i > 0) result += " ";
result += words[i];
}
return result;
}
};
int main() {
Solution solution;
string sentence = "I speak Goat Latin";
string transformed = solution.toGoatLatin(sentence);
cout << transformed << endl;
return 0;
}
Overall, the time complexity is O(n), where n is the total length of the input sentence.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?