Leetcode201: Remove Duplicate Letters

来源:互联网 发布:闲杂软件 编辑:程序博客网 时间:2024/04/29 17:57

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, check if the previously included letter in res (from back to begin) if larger than s[i], if yes and such res.back() letter has occurence after the current position i, then 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 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 sLen = s.size(), i, lastIdx[26]={0},resLen=0, included[26]={0};        string res;        for(i=sLen-1; i>=0 && resLen<26;--i)        {//generate lastIdx array           if(!lastIdx[s[i]-'a']) {            lastIdx[s[i]-'a'] = i;             ++resLen;           }         }        for(i=0; i<sLen;++i)         { //scan s from left to right            if(!included[s[i]-'a'])            { // if s[i] is not included in s[i]                while(!res.empty() && s[i]<res.back() && lastIdx[res.back()-'a']>i)                { // pop res as much as possible to reduce res                    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;    }};


0 0
原创粉丝点击