题解 | #DNA序列#
DNA序列
https://www.nowcoder.com/practice/e8480ed7501640709354db1cc4ffd42a
import java.util.*; import java.util.concurrent.atomic.AtomicReference; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case String a = in.nextLine(); int b = Integer.parseInt(in.nextLine()); System.out.println(new Main().gcration(a, b)); } } String gcration(String s, int N) { LinkedHashMap<String, Integer> hm = new LinkedHashMap<>();//存放子串及其中GC的个数 for (int i = 0; i <= s.length() - N; i++) {//由左至右逐个取长度为N的子串 String ss = s.substring(i, i + N); String ss0 = ss.replaceAll("[GC]", ""); if (!hm.containsValue(ss)) { hm.put(ss, ss.length() - ss0.length());//计算子串中GC的个数并存入映射 } } int max = hm.values().stream().max(Comparator.naturalOrder()).get();//找出映射的value集中最大的那个 //使用map的stream流中的的anyMatch功能找出第一个value等于max的key值(也可以直接用for循环) AtomicReference<String> out = new AtomicReference<>(""); hm.entrySet().stream().anyMatch(en -> { if (en.getValue().intValue() == max) { out.set(en.getKey()); return true; } else { return false; } }); return out.get(); } }