题意:给定一个句子,把它的每个词转成山羊拉丁文
思路:
- 把字符串用“ ”分割
- 遍历分割后的字符串数组
- 对每一个单词,调用trim切除首尾的“ ”,如果长度是0,跳过
- 每次遍历增加一个a到enda stringbuider
- 如果首字符是aeiou的大小写,那么就按照规则,把当前词加入结果,并在词末尾加ma以及enda以及“ ”
- 如果首字符不是元音字符,那么就按照规则,把但前词除首字符之外的字符加入结果,并在词末尾加上首字符以及ma以及enda以及“ ”
- 返回trim后的字符
思想:字符串组合
复杂度:时间O(n),空间O(n)
class Solution {
public String toGoatLatin(String S) {
String[] strs = S.split(" ");
StringBuilder res = new StringBuilder();
StringBuilder enda = new StringBuilder();
for(String s: strs) {
s = s.trim();
if(s.length() == 0)
continue;
enda.append('a');
char c = s.charAt(0);
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
res.append(s + "ma").append(enda).append(" ");
} else {
res.append(s.substring(1)).append(c).append("ma").append(enda).append(" ");
}
}
return res.toString().trim();
}
}
网友评论