824. Goat Latin - LeetCode

Questioin

824. Goat Latinjava

Solution

題目大意:根據要求翻譯句子數組

思路:轉換成單詞數組,遍歷數組,根據要求轉換單詞app

Java實現:ui

用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();
}

相關文章
相關標籤/搜索