算法笔记: 力扣#824 山羊拉丁文

问题描述


解法


分析

Python 实现

1
2
3
4
5
6
7
8
9
10
11
12
class :
def toGoatLatin(self, S):
"""
:type S: str
:rtype: str
"""
def process(word, idx):
if word[0] not in 'aeiouAEIOU':
word = word[1:] + word[0]
return word + "ma" + "a" * (idx+1)
return " ".join(process(word, idx) for idx, word in enumerate(S.split()))

Java 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class {
public String toGoatLatin(String S) {
Set<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
StringBuilder ans = new StringBuilder();
String tail = "";
for(String word : S.split(" ")){
if(vowels.contains(word.charAt(0))){
ans.append(word);
}else{
ans.append(word.substring(1) + word.substring(0, 1));
}
ans.append("ma");
tail += "a";
ans.append(tail + " ");
}
ans.deleteCharAt(ans.length() - 1);
return ans.toString();
}
}

时间复杂度

O(N).

空间复杂度

O(N).

链接


824. Goat Latin
824. 山羊拉丁文
(English version) Algorithm Notes: Leetcode#824 Goat Latin