A sentence S
is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.)
The rules of Goat Latin are as follows:
- If a word begins with a vowel (a, e, i, o, or u), append
"ma"
to the end of the word.
For example, the word 'apple' becomes 'applema'.
- If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add
"ma"
.
For example, the word"goat"
becomes"oatgma"
.
- Add one letter
'a'
to the end of each word per its word index in the sentence, starting with 1.
For example, the first word gets"a"
added to the end, the second word gets"aa"
added to the end and so on.
Return the final sentence representing the conversion from S
to Goat Latin.
Example 1:
Input: "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
Approach
Java
public class GoatLatin {public static void main(String[] args) {String str = "I speak Goat Latin";System.out.println(toGoatLatin(str));}static String toGoatLatin(String S) {String str = "";int i = 0;int cnt = 1;int n = S.length();while (i < n) {String str1 = "";while (i < n && S.charAt(i) == ' ')i++;while (i < n && S.charAt(i) != ' ') {str1 += S.charAt(i);i++;}if (isvowel(str1.charAt(0))) {str += str1;str += "ma";for (int j = 1; j <= cnt; j++)str += "a";if (i != n)str += " ";} else {for (int j = 1; j < str1.length(); j++)str += str1.charAt(j);str += str1.charAt(0);str += "ma";for (int j = 1; j <= cnt; j++)str += "a";if (i != n)str += " ";}cnt++;}return str;}// function to check for the// character is vowel or notstatic boolean isvowel(char c) {if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')return true;if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')return true;return false;}}
C++
#include <bits/stdc++.h>using namespace std;//function to check for the//character is vowel or notbool isvowel(char c){if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')return true;if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')return true;return false;}string toGoatLatin(string S){string str = "";string x = "";int i = 0;int cnt = 1;int n = S.size();while (i < n){string str1 = "";while (i < n && S[i] == ' ')i++;while (i < n && S[i] != ' '){str1 += S[i];i++;}if (isvowel(str1[0])){str += str1;str += "ma";for (int j = 1; j <= cnt; j++)str += "a";if (i != n)str += " ";}else{for (int j = 1; j < str1.size(); j++)str += str1[j];str += str1[0];str += "ma";for (int j = 1; j <= cnt; j++)str += "a";if (i != n)str += " ";}cnt++;}return str;}int main(){string str = "I speak Goat Latin";cout << toGoatLatin(str);return 0;}
No comments:
Post a Comment