[leetcode]316. Remove Duplicate Letters

题目链接: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;ii)
                {
                    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;
    }
};


你可能感兴趣的:(leetcode,贪心)