题解 | #DNA序列#

DNA序列

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

#include <iostream>
using namespace std;

int main() {
    string str;
    int len;
    cin >> str >> len;
    // 滑动窗口
    // 计算子串的CG比例
    auto computeRatio = [] (string subStr) {
        int count = 0;
        for (auto& c : subStr) {
            if (c == 'C' || c == 'G') {
                count++;
            }
        }
        return double(count) / double(subStr.size());
    };
    double maxRatio = 0;
    // 维护有最大比值的左右区间
    int leftMax = 0, rightMax = str.size();
    for (int i = 0, j = len; j <= str.size(); j++) {
        // 如果当前区间大于len
        while (j - i >= len) {
            // 获取当前的子串及比率
            auto curStr = str.substr(i, j - i);
            auto curRatio = computeRatio(curStr);
            // 如果比最大比率大,更新左右区间和比率
            if (curRatio > maxRatio) {
                leftMax = i;
                rightMax = j;
                maxRatio = curRatio;
            }
            // 将左端点溢出
            i++;
        }
    }
    cout << str.substr(leftMax, rightMax - leftMax) << endl;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

06-07 17:17
嘉兴学院 教师
单单人旁的佳:你是我见过最美的牛客女孩
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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