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. class Solution { public String toGoatLatin(String S) { Setvowels = getVowels(); String[] words = S.split("\\s+"); String a = "a"; for (int i = 0; i < words.length; i++) { String word = words[i]; if (!vowels.contains(word.charAt(0))) { words[i] = word.substring(1) + word.charAt(0); } words[i] += "ma" + a; a += "a"; } return String.join(" ", words); } private Set getVowels() { Set s = new HashSet<>(); s.add('a'); s.add('e'); s.add('i'); s.add('o'); s.add('u'); s.add('A'); s.add('E'); s.add('I'); s.add('O'); s.add('U'); return s; } }
No comments:
Post a Comment