Description:
A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to “Goat Latin” (a made-up language similar to Pig Latin.)
The rules of Goat Latin are as follows:
-
If a word begins with a vowel (a, e, i, o, or u), append “ma” to the end of the word.
For example, the word ‘apple’ becomes ‘applema’. -
If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add “ma”.
For example, the word “goat” becomes “oatgma”. -
Add one letter ‘a’ to the end of each word per its word index in the sentence, starting with 1.
For example, the first word gets “a” added to the end, the second word gets “aa” added to the end and so on.
Return the final sentence representing the conversion from S to Goat Latin.
Example 1:
Input: "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
Example 2:
Input: "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
Notes:
- S contains only uppercase, lowercase and spaces. Exactly one space between each word.
- 1 <= S.length <= 150.
题意:给定一个字符串,将字符串中的每个单词按照如下的规则进行转换后返回;
- 如果单词的首字母是元音(a, e, i, o, u;包括大写),那么返回的是这个单词后加上字符串"ma"
- 如果单词的首字母不是元音,那么将这个单词的首字母移动到单词的末尾后加上字符串"ma"
- 在每个单词的末尾还要加上字符串"a…a",a重复的长度为当前遍历的数组的下标+1;
解法:将给定的字符串按照空格进行分割后得到字符串数组,遍历每个字符串,按照上述的规则进行转换后返回得到的结果;
Java
class Solution {
public String toGoatLatin(String S) {
StringBuilder result = new StringBuilder();
StringBuilder end = new StringBuilder("a");
String ma = "ma";
String[] words = S.split("\u0020");
for (String word : words) {
if (isVowel(Character.toLowerCase(word.charAt(0)))) {
result.append(word + "ma");
} else {
result.append(word.substring(1) + word.charAt(0) + ma);
}
result.append(end.toString() + '\u0020');
end.append("a");
}
return result.toString().trim();
}
private boolean isVowel(char ch) {
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ? true : false;
}
}