[leetcode] 316. Remove Duplicate Letters 解题报告

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

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"


思路: 先对字符进行计数, 然后再遍历一遍数组, 如果当前字符没有出现在结果结果中, 并且比结果中最后一个字符小, 并且那个字符以后还会出现, 那就将其从结果集合中删除. 否则就将其加入结果集合.

代码如下:

class Solution {
public:
    string removeDuplicateLetters(string s) {
        unordered_map hash, visited;
        for(auto ch: s) hash[ch]++;
        string ans;
        for(int i =0; i < s.size(); i++)
        {
            hash[s[i]]--;
            if(visited[s[i]]) continue;
            while(ans.size()!=0 && hash[ans.back()] && s[i]
参考: https://leetcode.com/discuss/75529/c-simple-solution-easy-understanding

你可能感兴趣的:(leetcode,greedy,string)