[笔试训练](十三)

目录

037:牛牛冲钻五

038:最长无重复子数组

039:重排字符串


037:牛牛冲钻五

牛牛冲钻五 (nowcoder.com)

题解:简单模拟

#include <iostream>
#include <string>
using namespace std;
int t, n, k;
string s;
int fun()
{
    int ret = 0;
    for(int i = 0; i < s.size(); i++)
    {
        if(s[i] == 'L')
        {
            ret--;
        }
        else
        {
            if(i - 1 >= 0 && i - 2 >= 0 && s[i - 1] == 'W' && s[i - 2] == 'W')
            {
                ret += k;
            }
            else
            {
                ret += 1;
            }
        }
    }
    return ret;
}

int main()
{
    cin >> t;
    while(t--)
    {
        cin >> n >> k >> s;
        cout << fun() << endl;
    }
    return 0;
}

038:最长无重复子数组

最长无重复子数组_牛客题霸_牛客网 (nowcoder.com) 

题解:经典滑动窗口

class Solution {
    int hash[100010]={0};
public:
    int maxLength(vector<int>& arr) 
    {
       //滑动窗口
       int n=arr.size();
       int right=0,left=0,ret=0;
       while(right<n)
       {
            hash[arr[right]]++;//进窗口
            while(hash[arr[right]]>1)//判断
            {
                hash[arr[left]]--;//出窗口
                left++;
            }
            ret=max(ret,right-left+1);
            right++;
       }
       return ret;
    }
};

039:重排字符串

重排字符串 (nowcoder.com)

题解:贪心

 

#include<iostream>
using namespace std;
const int N=1e5+10;

int cnt[26]={0};
char s[N];
char ret[N];
int n;
int main()
{
    cin>>n>>s;
    char maxchar;
    int maxcount=0;
    for(int i=0;i<n;i++)
    {
        cnt[s[i]-'a']++;
        if(cnt[s[i]-'a']>maxcount)
        {
            maxcount=cnt[s[i]-'a'];
            maxchar=s[i];
        }
    }
    cout<<maxcount<<" "<<maxchar<<endl;
    if(maxcount>(n+1)/2) cout<<"No"<<endl;
    else
    {
        cout<<"Yes"<<endl;
        int index=0;
        //先填最多数量的字符
        while(maxcount--)
        {
            ret[index]=maxchar;
            index+=2;
        }
        
        //填剩下的
        for(int i=0;i<26;i++)
        {
            if(cnt[i] && i+'a'!=maxchar)
            {
                while(cnt[i]--)
                {
                   if(index>=n) index=1;
                    ret[index]=i+'a';
                    index+=2; 
                }
            }
        }
    }
    //打印结果
    for(int i=0;i<n;i++)
    {
        cout<<ret[i];
    }
    cout<<endl;
    
    return 0;
}
  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敲敲er

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值