DNA序列

題目描述

一個DNA序列由A/C/G/T四個字母的排列組合組成。G和C的比例(定義爲GC-Ratio)是序列中G和C兩個字母的總的出現次
數除以總的字母數目(也就是序列長度)。在基因工程中,這個比例很是重要。由於高的GC-Ratio多是基因的起始點。

給定一個很長的DNA序列,以及要求的最小子序列長度,研究人員常常會須要在其中找出GC-Ratio最高的子序列。

輸入描述

輸入一個string型基因序列,和int型子串的長度

輸出描述

找出GC比例最高的字串

輸入例子

AACTGTGCACGACCTGA
5

輸出例子

GCACG

算法實現

import java.util.Scanner;

/**
 * All Rights Reserved !!!
 */
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
//        Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
        while (scanner.hasNext()) {
            String input = scanner.nextLine();
            int n = scanner.nextInt();
            System.out.println(maxRatio(input, n));
        }

        scanner.close();
    }

    /**
     * 初始化兩個數組,一個序列數值數組K[N],一個序列和數組SUM[N],先遍歷一邊序列,
     * 爲C或者G則K[i]爲1,不然則置爲0,而後計算連續M個K[I]之和存入SUM就行。
     *
     * @param s
     * @param m
     * @return
     */
    private static String maxRatio(String s, int m) {
        int[] k = new int[s.length()];
        int[] sum = new int[s.length()];
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == 'C' || c == 'G') {
                k[i]++;
            }
        }

        for (int i = 0; i < k.length - m; i++) {
            for (int j = 0; j < m; j++) {
                sum[i] += k[i + j];
            }
        }

        int max = 0;
        int idx = 0;
        for (int i = 0; i < k.length - 1; i++) {
            if (sum[i] > max) {
                max = sum[i];
                idx = i;
            }
        }

        return s.substring(idx, idx + m);
    }
}
相關文章
相關標籤/搜索