LintCode 1560. 最小字符串

Given a string s of lowercase letters of length n, remove the k characters from it and we will get a new string of length n-k. Please output the new string with the smallest lexicographic order.

The lexicographical order in this problem: Firstly compare the length of two strings, the lexicographical order of the smaller length is smaller. If the length is the same, then comparison is started from the left side of the string to find the first different character, and the corresponding character smaller is the smaller lexicographical order string.

For example: “abbz” and “abza”
Firstly two strings are the same length, then compare bit by bit from the left:
The first bit is “a”, then continue to compare the next one
The second bit is “b”, then continue to compare the next one
For third bit, the first string is “b”, and the second string is “z”. Because “b” < “z”, the lexicographic order of the first string is smaller.

样例
给定s=”abccc”,k=2,返回 “abc”

解释:
删除4号位和5号位的c
给定 s=”bacdb”,k=2,返回”acb”

解释:
删除1号位的b和4号位的d
给定s=”cba”,k=2,返回”a”

解释:
删除1号位的c和2号位的b
注意事项
0 \leq k < n \leq 1000000≤k

/**
* 本参考程序来自九章算法,由 @弈助教 提供。版权所有,转发请注明出处。
* - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
* - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班,
* - Big Data 项目实战班,算法面试高频题班, 动态规划专题班
* - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code
*/ 
const int N = 2e5 + 50;
char stk[N];
class Solution {
public:
    /**
     * @param s: the string
     * @param k: the max time to remove characters
     * @return: Please output the new string with the smallest lexicographic order.
     */
    string MinimumString (string &s, int k) {
        // Write your code here
        int n = s.length(), i, j, cnt = 0, tp = 0;
        for (i = 0; i < n; i++) {
            while (tp && k && stk[tp] > s[i]) {
                tp--;
                k--;
            }
            stk[++tp] = s[i];
        }
        stk[tp + 1 - k] = '\0';
        string ans = stk + 1;
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值