题解:P16841 [GKS 2021 #B] Increasing Substring

· · 题解

题意

给出一个N与字符串S,要求不断输出在字符串S中的连续递增字符个数 。

思路

设一个变量 cnt 表示当前结尾的最长递增子串长度。

这样只需一次 O(N) 的循环,空间 O(1),可以处理 N \le 2 \times 10^5 的数据。

题解

#include <bits/stdc++.h>
using namespace std;
void solve(int t)
{
    int n;
    string s;
    cin>>n>>s;
    cout<<"Case #"<<t<<": 1";
    int cnt=1;//连续递增长度
    for(int i=1;i<n;i++)
    {
        if(s[i]>s[i-1])//判断当前字符是否大于前一个字符 。
        {
            cnt++;//是,就让连续个数加1 。
        }
        else
        {
            cnt=1;//否则就让连续个数变为1个 。
        }
        cout<<" "<<cnt;//不断输出连续个数 。
    }
    cout<<endl;
}
int main()
{
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);//提升代码运行效率 。
    int T=1;
    cin>>T;
    for(int t=1;t<=T;t++)
    {
        solve(t);
    }
    return 0;
}

复杂度分析

时间复杂度 O(N),空间复杂度 O(1),可处理 N \le 2 \times 10^5