Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.
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.
Note: This question is the same as 316:
今天這題給我們一個字串 s,
題目希望我們從 s 裡面找出最小字典序。
這題我原本用 map 紀錄每個字元的出現紀錄,
如果這個字元拿到最後一個就強制加入答案,
其餘就是用字元前後順序來加入答案。
但是我這想法不行,
不行在字元前後順序可能被跳過,
以測資二來舉例:
Input: s = "cbacdcbc"
Output: "acdb"
但是我輸出會變成:"adbc"
因為我看到 d 的時候觸發自己的第一條規則(#。
這問題就是要改進第二條規則,
要關注所有的候選者,
所以先加入,再決定要不要 pop 掉。
C++程式碼:
假設 s 的長度是 N。
計算複雜度:O(N)
-> 就算被 pop 掉,每個元素也最多被考慮兩次。
空間複雜度:O(N)
Github程式碼: