[leetcode]316. Remove Duplicate Letters

本文介绍了一种移除字符串中重复字母的算法,确保每个字母只出现一次,并保持结果字典序最小。通过记录每个字符最后一次出现的位置及是否已加入结果串的状态,采用贪心策略实现高效处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://leetcode.com/problems/remove-duplicate-letters/description/

Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

Example:

Given "bcabc"
Return "abc"

Given "cbacdcbc"
Return "acdb"


The key is to get an auxiliary array to save the index of the last occurence of each letter in S. Then we do greedy algorithm: scan the string from left to right, for the current letter s[i], if it is already included then move on, if not, firstly check if the res from back to begin is larger than s[i] and will occur after the current position i. If meet both condition,  drop it from res and reset the included flag (since it can reduce res and res.back() can still be added back later on), and repeat to check the new res.back(). If res.empty() or s[i]> res.back() or res.back() has no occurence after i, then, just add s[i] to res.
Two key arrays are used in the following code
lastIdx[i]: the last occurence index of letter 'a'+i in s
included[i]: if 'a'+i is already included in res


class Solution {
public:
    string removeDuplicateLetters(string s) {
        int lastIdx[26]={0},included[26]={0};
        string res;
        //generate lastIdx array
        for(int i=0;i<s.size();i++)
            lastIdx[s[i]-'a']=i;

        //scan s from left to right
        for(int i=0;i<s.size();i++)
        {
            // if s[i] is not included
            if(!included[s[i]-'a'])
            {
                // pop res as much as possible to reduce res
                while(!res.empty() && s[i]<res.back() && lastIdx[res.back()-'a']>i)
                {
                    included[res.back()-'a']=0;
                    res.pop_back();
                }
                included[s[i]-'a']=1;
                // add s[i] to res
                res.push_back(s[i]);
            }
        }
        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值