1
+ /*
2
+ Author: Junhua Chang, junhuac@hotmail.com
3
+ Date: Dec 5, 2020
4
+ Problem: Goat Latin
5
+ Difficulty: Low
6
+ Source: https://leetcode.com/problems/goat-latin/
7
+ Notes:
8
+ A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.
9
+
10
+ We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.)
11
+
12
+ The rules of Goat Latin are as follows:
13
+
14
+ If a word begins with a vowel (a, e, i, o, or u), append "ma" to the end of the word.
15
+ For example, the word 'apple' becomes 'applema'.
16
+
17
+ 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".
18
+ For example, the word "goat" becomes "oatgma".
19
+
20
+ Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1.
21
+ For example, the first word gets "a" added to the end, the second word gets "aa" added to the end and so on.
22
+ Return the final sentence representing the conversion from S to Goat Latin.
23
+
24
+
25
+
26
+ Example 1:
27
+
28
+ Input: "I speak Goat Latin"
29
+ Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
30
+ Example 2:
31
+
32
+ Input: "The quick brown fox jumped over the lazy dog"
33
+ Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
34
+
35
+
36
+ Notes:
37
+
38
+ S contains only uppercase, lowercase and spaces. Exactly one space between each word.
39
+ 1 <= S.length <= 150.
40
+ */
41
+
42
+ class Solution {
43
+ public String toGoatLatin (String S ) {
44
+
45
+ StringBuilder sb =new StringBuilder ();
46
+ boolean bStart =true ;
47
+ String vowels ="aeiouAEIOU" ;
48
+ char ch =0 ;
49
+ char consonant =0 ;
50
+ int index =0 ;
51
+
52
+ for (int i =0 ;i <S .length ();i ++)
53
+ {
54
+ ch =S .charAt (i );
55
+
56
+ if (ch ==' ' )
57
+ {
58
+ bStart =true ;
59
+ sb .append (ch );
60
+ continue ;
61
+ }
62
+
63
+ if (bStart )
64
+ {
65
+ index ++;
66
+ if (vowels .indexOf (ch ) >=0 )
67
+ {
68
+ consonant =0 ;
69
+ sb .append (ch );
70
+ }
71
+ else
72
+ {
73
+ consonant =ch ;
74
+ }
75
+ bStart =false ;
76
+ }
77
+ else
78
+ {
79
+ sb .append (ch );
80
+ }
81
+
82
+ if ((i ==S .length ()-1 ) ||S .charAt (i +1 ) ==' ' )
83
+ {
84
+ if (consonant !=0 )
85
+ {
86
+ sb .append (consonant );
87
+ }
88
+ sb .append ("ma" );
89
+ for (int j =0 ;j <index ;j ++)
90
+ {
91
+ sb .append ("a" );
92
+ }
93
+ continue ;
94
+ }
95
+ }
96
+
97
+ return sb .toString ();
98
+ }
99
+ }