百度2018秋招笔试题之最大子序列

对于字符串x和y, 如果擦除x中的某些字母(有可能全擦掉或者都不擦)能够得到y,我们就称y是x的子序列。例如."ncd"是"nowcoder"的子序列,而"xt"不是。
现在对于给定的一个字符串s,请计算出字典序最大的s的子序列。

输入描述:

输入包括一行,一个字符串s,字符串s长度length(1 ≤ length ≤ 50).
s中每个字符都是小写字母

输出描述:

输出一个字符串,即字典序最大的s的子序列。

示例1

输入

test

输出

tt

知识点:C++ STL,字符操作

#include <bits/stdc++.h>
using namespace std;
string s;
int main()
{
    cin>>s;
    ostringstream ss;
    while(!s.empty()){
        string::iterator it = max_element(s.begin(),s.end());
        ss<<*it;
        s.erase(s.begin(),it+1);
    }
    cout<<ss.str()<<endl;
    return 0;
}

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main
{
    static StringBuilder solve(String x)
    {
        StringBuilder y=new StringBuilder();
        y.append(x.charAt(x.length()-1));
        int i=x.length()-2;
        while(i>=0)
        {
            if(x.charAt(i)>=y.charAt(y.length()-1))
                y.append(x.charAt(i));
            i--;
        }
        return y.reverse();
    }
    public static void main(String[] args) throws IOException
    {
        BufferedReader scanner = new BufferedReader(new InputStreamReader(System.in));
        String x= scanner.readLine();
        System.out.println(solve(x));
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值