java codility training Genomic-range-query

后端 未结 30 2276
悲哀的现实
悲哀的现实 2021-02-01 12:47

The task is:

A non-empty zero-indexed string S is given. String S consists of N characters from the set of upper-case English letters A, C, G, T.

<
30条回答
  •  野的像风
    2021-02-01 13:49

    I think I'm using dynamic programming. Here is my solution. Little space. Code is mot really clean, just show my idea.

    class Solution {
    public int[] solution(String S, int[] P, int[] Q) {
        int[] preDominator = new int[S.length()];
        int A = -1;
        int C = -1;
        int G = -1;
        int T = -1;
    
        for (int i = 0; i < S.length(); i++) {
            char c = S.charAt(i);
            if (c == 'A') { 
                A = i;
                preDominator[i] = -1;
            } else if (c == 'C') {
                C = i;
                preDominator[i] = A;
            } else if (c == 'G') {
                G = i;
                preDominator[i] = Math.max(A, C);
            } else {
                T = i;
                preDominator[i] = Math.max(Math.max(A, C), G);
            }
        }
    
        int N = preDominator.length;
        int M = Q.length;
        int[] result = new int[M];
        for (int i = 0; i < M; i++) {
            int p = P[i];
            int q = Math.min(N, Q[i]);
            for (int j = q;;) {
                if (preDominator[j] < p) {
                    char c = S.charAt(j);
                    if (c == 'A') {
                        result[i] = 1;
                    } else if (c == 'C') {
                        result[i] = 2;
                    } else if (c == 'G') {
                        result[i] = 3;
                    } else {
                        result[i] = 4;
                    }
                    break;
                }
                j = preDominator[j];
            }
        }
        return result;
    }
    

    }

提交回复
热议问题