题解 | #DNA序列#

DNA序列

https://www.nowcoder.com/practice/e8480ed7501640709354db1cc4ffd42a

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String dnaStr = sc.nextLine();
        int num = sc.nextInt();
        //遍历str的所有长度为n的子串,过程中通过两个变量分别保存每次符合的子串的起始索引和CG个数
        Map<Integer, Integer> map = new TreeMap<>();
        for (int i = 0; i <= dnaStr.length() - num; i++) {
            String substring = dnaStr.substring(i, i + num);
            char[] chars = substring.toCharArray();
            int count = 0;
            for (char c : chars) {
                if (c == 'C' || c == 'G') {
                    count++;
                }
            }
            map.put(i, count);
        }

        int max = 0;
        int index = 0;//起始索引
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() > max) {
                max = entry.getValue();
                index = entry.getKey();
            }
        }
        System.out.println(dnaStr.substring(index, index + num));
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务