gpt4 book ai didi

java - 计算字符串数组中字符的出现次数

转载 作者:行者123 更新时间:2023-12-02 09:05:51 26 4
gpt4 key购买 nike

我正在编写一个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 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

关于java - 计算字符串数组中字符的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59817923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com