题解 | #DNA序列#

DNA序列

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

滑动窗口/前后指针
import java.util.Scanner;
import java.io.IOException;

public class Main{
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        String dna = sc.nextLine();
        int length = Integer.parseInt(sc.nextLine());
        if (length > dna.length()){
            System.out.println(dna);
            return;
        }
        int left = 0;
        int right = length - 1;
        int count = 0;
        int result = 0;
        for(int i = 0; i < length; ++i){
            if(dna.charAt(i) == 'C' || dna.charAt(i) == 'G'){
                count++;
            }
        }
        result = count;
        for(int i = 1, j = length; j < dna.length(); ++i, ++j){
            if(dna.charAt(i - 1) == 'C' || dna.charAt(i - 1) == 'G'){
                count--;
            }
            if(dna.charAt(j) == 'C' || dna.charAt(j) == 'G'){
                count++;
            }
            if(result < count){
                left = i;
                right = j;
                result = count;
            }
        }
        System.out.println(dna.substring(left, right + 1));
    }
}


全部评论

相关推荐

04-28 11:34
西北大学 运营
牛客4396号:不好意思,这个照片猛一看像丁真
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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