【问题标题】:Counting occurrence of char in array of string计算字符串数组中字符的出现次数
【发布时间】:2020-05-06 03:30:15
【问题描述】:

我正在编写一个 Java 程序,它计算数组(核苷酸序列列表)中字符串(核苷酸序列)中特定字符(nuc)的出现。它旨在返回字符出现次数最多的字符串。

输入:字符串列表(例如 {"aaagt","cgaat","ttt"} ),char = "a" / 输出:“aaagt”(因为“a”的出现次数最多)

下面,我有我写的 Python 版本。我如何将它翻译成 Java?

def DNAMaxNucleiotide(listStrings, nuc):
    nucCount = 0
    SEQ = ''

    for seq in listStrings:
        newCount = 0
        splitSeq = list(seq)
        for char in splitSeq:
            if char == nuc:
                newCount += 1
        if newCount > nucCount:
            nucCount = newCount
            SEQ = seq
        else:
            pass


    return SEQ

谢谢!

【问题讨论】:

标签: java string loops slice


【解决方案1】:

这是一种方法,在 Java 8+ 中:

static String dnaMaxNucleiotide(int codePoint, String... listStrings) {
    return Stream.of(listStrings)
            .max(Comparator.comparingLong(s -> countChar(codePoint, s)))
            .orElse("");
}
private static long countChar(int codePoint, String s) {
    return s.codePoints()
            .filter(cp -> cp == codePoint)
            .count();
}

测试

System.out.println(dnaMaxNucleiotide('a', "aaagt","cgaat","ttt"));

输出

aaagt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-24
    • 2020-02-21
    • 2012-02-12
    • 1970-01-01
    • 2023-02-04
    相关资源
    最近更新 更多