【leetcode刷题笔记】1081. 不同字符的最小子序列

题目链接(https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters/)

思路

要得到一个字典序最小的字符串,并且把给定的字符串中的每个字母都包含一次,所以我先用num数组记录给定字符串中出现的字母个数,再使用一个used数组来保证答案中包含给定字符串中每个字母的次数为1,开始遍历给定字符串,num减1,如果used[index]为1我就直接无视这个位置字母,因为要保证字典序最小所以比较ans末尾字符和给定字符串当前位置字符的大小,如果ans末尾字符大就出栈,循环这个过程直到ans为空或者ans末尾字符小于给定字符串当前位置字符的大小,类似于单调栈的思路

代码

class Solution
{
     
public:
    string smallestSubsequence(string text) 
    {
     
        string ans = "";
        vector<int> num(26, 0); //记录26个字母在字符串的次数
        vector<int> used(26, 0); //要让每个字母只使用1次
        for(int i = 0; i < text.size(); i++)
        {
     
            num[text[i] - 'a']++;
        }
        
        for(int i = 0; i < text.size(); i++)
        {
     
            num[text[i] - 'a']--;
            if(used[text[i] - 'a'])
                continue;    //此字母使用过一次直接无视
            while(!ans.empty() && ans.back() > text[i] && num[ans.back() - 'a'])
            {
     
                used[ans.back() - 'a']--;
                ans.pop_back();
            }
            ans.push_back(text[i]);
            used[text[i] - 'a']++;
        }
        return ans;
    }
};

你可能感兴趣的:(leetcode刷题笔记,c++,leetcode)