字符串计数问题(稳定基因问题)

字符串计数问题(稳定基因问题)

在字符串问题中有一类计数问题,许多字符串问题可以最终归结为计数问题,一个典型的代表是稳定基因问题。这个问题淋漓尽致地体现了解决这种问题的思路。

问题描述

给定一个基因序列A,该基因是成为稳定基因,必须满足如下约束:
- 基因序列A的长度为4*N;
- 基因序列中每个碱基的数量都是N。

解决思路:

解决的思路非常具有技巧性,这种技巧主要体现在如何使用map来计数的。如果我们替换的区间是A[i,j], 那么j - i + 1应该最小。下面我们来看如何求这个最小值。我们可以使用逆向思维,假定除去A[i,j],剩下元素中各个碱基的数量应该不会超过N,如果某个碱基的数量超过了N说明A[i,j]的长度不足,应该继续加长。
算法的流程如下:

  1. 用map从右向左统计各个碱基的数量,当某个碱基的数量等于N时停止并记下当前位置maxIndex。
  2. 从左往右设置minIndex并检查最短的A[i,j], 记录答案。
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
bool check(unordered_map<char,int>& dict, int N) {
    if (dict['C']<=N&&dict['G']<=N
        &&dict['T']<=N&&dict['A']<=N){
        return true;
    }
    return false;
}
int calculate(string& genes) {
    unordered_map<char, int> dict;
    int N = genes.size() / 4;
    int maxIndex = 0;
    for (int i = genes.size() - 1; i >= 0; --i) {
        if (dict.find(genes[i]) == dict.end()) {
            dict[genes[i]] = 1;
        } else {
            dict[genes[i]] += 1;
        }
        if (!check(dict, N)) {
            maxIndex = i + 1;
            dict[genes[i]] -= 1;
            break;
        }
    }
    //cout<<maxIndex<<endl;
    if (maxIndex == 0) {
        return 0;
    }
    int minIndex = -1;
    int ans = numeric_limits<int>::max();
    while (maxIndex < genes.size()
        && minIndex < maxIndex) {
        while(maxIndex < genes.size() && !check(dict, N)) {
            dict[genes[maxIndex]] -= 1;
            maxIndex += 1;
        }
        if (maxIndex - minIndex < ans) {
            ans = maxIndex - minIndex;
        }
        dict[genes[minIndex++]] += 1;
    }
    return ans;
}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int N = 0;
    string s;
    cin>>N>>s;
    int ans = calculate(s);
    cout<<ans<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值