b_mt_包裹区间分组(读题+滑窗)

有26名骑手,分别以大写字母A-Z命名,有一组包裹流 s,请在不打乱流水线产出顺序的情况下,把这组包裹划分为尽可能多的片段,同一个骑手只会出现在其中的一个片段,返回一个表示每个包裹片段的长度的列表。

输入
MPMPCPMCMDEFEGDEHINHKLIN
输出
9 7 8(划分结果为MPMPCPMCM,DEFEGDE,HINHKLIN)

思路:不断向后找当前字符的最后一个出现的位置;优化:可以先预处理一个 last_of 数组记录这些位置

#include<bits/stdc++.h>
using namespace std;
int main() {
    std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    string s; cin>>s;
    int n=s.size();
    for (int i=0; i<n;) {
        int j=s.find_last_of(s[i]);
        int k=i;
        for (; k<j; k++) {
            int t=s.find_last_of(s[k]);
            if (t>j) j=t;
        }
        cout<<k-i+1<<' ';
        i=k+1;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/wdt1/p/14527964.html