# 1081. Smallest Subsequence of Distinct Characters

Return the lexicographically smallest subsequence of `s` that contains all the distinct characters of `s` exactly once.

Note: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/

Example 1:

``````Input: s = "bcabc"
Output: "abc"
``````

Example 2:

``````Input: s = "cbacdcbc"
Output: "acdb"
``````

Constraints:

• `1 <= s.length <= 1000`
• `s` consists of lowercase English letters.

``````class Solution {
public:
string smallestSubsequence(string s) {
string res = "0";
vector<int> cnt(128), visited(128);
for (char c : s) ++cnt[c];
for (char c : s) {
--cnt[c];
if (visited[c]) continue;
while (c < res.back() && cnt[res.back()]) {
visited[res.back()] = 0;
res.pop_back();
}
res += c;
visited[c] = 1;
}
return res.substr(1);
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1081

Remove Duplicate Letters

https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/

https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/discuss/308194/C%2B%2B-O(n)-identical-to-316

https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/discuss/308210/JavaC%2B%2BPython-Stack-Solution-O(N)

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation