题目
算法中级:儿童黑话
在这道题目中,我们需要写一个函数,把传入的字符串翻译成“儿童黑话”。
儿童黑话的基本转换规则很简单,只需要把一个英文单词的第一个辅音字母或第一组辅音从移到单词的结尾,并在后面加上ay即可。在英语中,字母 a、e、i、o、u 为元音,其余的字母均为辅音。辅音从的意思是连续的多个辅音字母。
额外地,如果单词本身是以元音开头的,那只需要在结尾加上way。
在本题中,传入的单词一定会是英文单词,且所有字母均为小写。
translatePigLatin(“california”)应该返回 “aliforniacay”。
translatePigLatin(“paragraphs”)应该返回 “aragraphspay”。
translatePigLatin(“glove”)应该返回 “oveglay”。
translatePigLatin(“algorithm”)应该返回 “algorithmway”。
translatePigLatin(“eight”)应该返回 “eightway”。
你的代码应当能够处理第一个元音字母在单词结尾的情况。比如translatePigLatin(“she”)应该返回 “eshay”。
你的代码应当能够处理单词中不含元音字母的情况。比如translatePigLatin(“rhythm”)应该返回 “rhythmay”。
解题
function translatePigLatin(str) {
let boo = false;
let index;
for (let i = 0; i < str.length; i++) {
switch (str[i]) {
case "a": boo = false; break;
case "e": boo = false; break;
case "i": boo = false; break;
case "o": boo = false; break;
case "u": boo = false; break;
default: boo = true; break;
}
if (!boo) {
if(i===0){
break;
}
index = i == 0 ? 0 : i - 1;
console.log(index);
break;
}
}
if (index >= 0||boo) {
str = str.slice(index + 1) + str.slice(0, index + 1) + "ay";
} else {
str = str + "way"
}
return str;
}
translatePigLatin("rhythm");