- 题目描述
- 思路
- 模拟
- Python实现
- Java实现
题目描述
山羊拉丁文
思路 模拟
遍历字符串,分割找到每个单词,依照题意进行 *** 作即可。
Python实现VOWELS = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}
class Solution:
def toGoatLatin(self, sentence: str) -> str:
n = len(sentence)
i, cnt = 0, 1
words = list()
while i < n:
j = i
while j < n and sentence[j] != " ":
j += 1
cnt += 1
if sentence[i] in VOWELS:
words.append(sentence[i:j] + "m" + "a" * cnt)
else:
words.append(sentence[i+1:j] + sentence[i] + "m" + "a" * cnt)
i = j + 1
return " ".join(words)
Java实现
class Solution {
private static final Set<Character> VOWELS = new HashSet<>();
static {
VOWELS.add('a');
VOWELS.add('e');
VOWELS.add('i');
VOWELS.add('o');
VOWELS.add('u');
VOWELS.add('A');
VOWELS.add('E');
VOWELS.add('I');
VOWELS.add('O');
VOWELS.add('U');
}
public String toGoatLatin(String sentence) {
StringBuilder sb = new StringBuilder();
int n = sentence.length(), cnt = 1;
for (int i = 0; i < n; i++) {
char ch = sentence.charAt(i++);
if (VOWELS.contains(ch)) {
sb.append(ch);
}
while (i < n && sentence.charAt(i) != ' ') {
sb.append(sentence.charAt(i++));
}
if (!VOWELS.contains(ch)) {
sb.append(ch);
}
sb.append("m");
for (int j = 0; j <= cnt; j++) {
sb.append("a");
}
if (i < n-1) {
sb.append(" ");
}
cnt++;
}
return sb.toString();
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)