给定一个句子,由大小写英文字母组成,以空格为单词的分割。.net
按如下规则修改单词:code
ma
;ma
;a
。n为当前单词在句子中的次序,从1开始。即,在第1个单词按以上规则转换完成后,再加1个a。在第2个单词末尾加2个a,第3个加3个a,以此类推。首先,须要把句子分割成单词。用str_explode就能够实现。leetcode
分割后,判断首字母是否不是元音。
不是元音,则将第一个字母移到最后。字符串
给字符串末尾添加ma
。
给字符串末尾添加额外的n
个a
。get
<?php class Solution { /** * @param String $S * @return String */ function toGoatLatin($S) { $words = explode(' ', $S); $newWords = []; foreach($words as $key => $word){ if(!in_array($word[0],['a','e','i','o','u','A','E','I','O','U'])){ $word .= $word[0]; $word = substr($word,1); } $word .= 'ma'.str_repeat('a', $key+1); $newWords[] = $word; } return implode(' ', $newWords); } }
若以为本文章对你有用,欢迎用爱发电资助。io