题解:P13189 [GCJ 2016 #1A] The Last Word

· · 题解

题意

题目给出一个字符串,让我们按字符串顺序将当前字符拼在新字符串的前面或后面,最后找到字典序最大的一个字符串。

思路

既然要找最大的,那么我们就可以在拼新字符串时作分类讨论,只要当前字符比新字符串的第 0 位大,那么就把他拼在前面,否则拼在后面。

代码

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin>>t;
    int cnt=0;
    while(t--)
    {
        cnt++;
        string s;
        cin>>s;
        int len=s.size();
        string ans="";
        for(int i=0;i<len;++i)
        {
            if(s[i]>=ans[0])
            {
                ans=s[i]+ans;
            }
            else
            {
                ans=ans+s[i];
            }
        }
        cout<<"Case #"<<cnt<<": "<<ans<<endl;
    }
    return 0;
}