leetcode-824-Goat-Latin

描述


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:

1
2
Input: "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"

Example 2:

1
2
Input: "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"

Notes:

  • S contains only uppercase, lowercase and spaces. Exactly one space between each word.
  • 1 <= S.length <= 150.

分析


按照三种转换规则一个单词一个单词进行处理即可。

解决方案1(Java)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public String toGoatLatin(String S) {
Set<Character> vowel = new HashSet<>();
for (char c: new char[]{'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}) {
vowel.add(c);
}
int indexNum = 1;
StringBuilder result = new StringBuilder();
for (String word: S.split("\\s")) {
char first = word.charAt(0);
if (vowel.contains(first)) {
result.append(word);
} else {
result.append(word.substring(1));
result.append(word.substring(0, 1));
}
result.append("ma");
for (int i = 0; i < indexNum; i++) {
result.append("a");
}
result.append(" ");
indexNum++;
}
result.deleteCharAt(result.length() - 1);
return result.toString();
}
}

解决方案2(Golang)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var vowelMap = map[byte]bool {
'a': true,
'e': true,
'i': true,
'o': true,
'u': true,
'A': true,
'E': true,
'I': true,
'O': true,
'U': true,
}

func toGoatLatin(sentence string) string {
sentenceSlice := strings.Split(sentence, " ")
result := make([]string, len(sentenceSlice))

i := 0
for _, word := range sentenceSlice {
now := []byte(word)
if _, ok := vowelMap[now[0]]; ok {
result[i] = word + "ma"
} else {
result[i] = word[1:] + word[0:1] + "ma"
}
result[i] = result[i] + strings.Repeat("a", i+1)
i++
}

return strings.Join(result, " ")
}

题目来源