824. Goat Latin - LeetCode

Posted okokabcd

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了824. Goat Latin - LeetCode相关的知识,希望对你有一定的参考价值。

Questioin

824.?Goat Latin

技术分享图片

Solution

题目大意:根据要求翻译句子

思路:转换成单词数组,遍历数组,根据要求转换单词

Java实现:

用Java8的流实现,效率太低

public String toGoatLatin(String S) {
    final String[] arr = S.split(" ");
    final int[] idx = {0};
    return Arrays.stream(S.split(" "))
        .map(s -> convert(s, ++idx[0]))
        .reduce("", (s1, s2) -> s1 + " " + s2).trim();
}

String convert(String ori, int count) {
    String pre = "";
    // begin with vowel aeiou
    char first = ori.charAt(0);
    if (first == 'A' || first == 'a'
        || first == 'E' || first == 'e'
        || first == 'I' || first == 'i'
        || first == 'O' || first == 'o'
        || first == 'U' || first == 'u'
       ) {
        pre = ori;
    } else {
        // begin with consonant not aeiou
        pre = ori.substring(1) + first;
    }

    // add a
    char[] a = new char[count];
    for (int i = 0; i < count; i++) {
        a[i] = 'a';
    }
    return pre + "ma" + String.valueOf(a);
}

技术分享图片

public String toGoatLatin(String S) {
    StringBuilder sb = new StringBuilder();
    int count = 1;
    for(String tmp : S.split(" ")) {
        sb.append(convert(tmp, count++)).append(" ");
    }
    return sb.toString().trim();
}

技术分享图片

以上是关于824. Goat Latin - LeetCode的主要内容,如果未能解决你的问题,请参考以下文章

824. Goat Latin

824. Goat Latin山羊拉丁文

LeetCode 824. Goat Latin (山羊拉丁文)

*LeetCode--Goat Latin

LeetCode 题解之Goat Latin

力扣leetcod 175:组合两个表