LeetCode 1081. Smallest Subsequence of Distinct Characters


原題鏈接在這里:https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/

題目:

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

Example 1:

Input: "cdadabcc"
Output: "adbc" 

Example 2:

Input: "abcd"
Output: "abcd" 

Example 3:

Input: "ecbacba"
Output: "eacb" 

Example 4:

Input: "leetcode"
Output: "letcod"

Note:

  1. 1 <= text.length <= 1000
  2. text consists of lowercase English letters.

題解:

Try to build the string greedily. Mark the last appearence of each char in text.

For current char c, if it is not already added. Keep check the last added char. If it is bigger than current c and that bigger char last appearence is after current index, then it means that this bigger char could be added later.

Pop it out and mark it as unused.

Now this makes sure that the char in stack are as small as possible.

Time Complexity: O(n). n = text.length().

Space: O(1). size 26.

AC Java:

 1 class Solution {
 2     public String smallestSubsequence(String text) {
 3         int [] last = new int[26];
 4         for(int i = 0; i<text.length(); i++){
 5             last[text.charAt(i)-'a'] = i;
 6         }
 7         
 8         Stack<Character> stk = new Stack<>();
 9         boolean [] used = new boolean[26];
10         for(int i = 0; i<text.length(); i++){
11             char c = text.charAt(i);
12             if(used[c-'a']){
13                 continue;
14             }
15             
16             while(!stk.isEmpty() && stk.peek()>c && last[stk.peek()-'a']>i){
17                 char top = stk.pop();
18                 used[top-'a'] = false;
19             }
20             
21             stk.push(c);
22             used[c-'a'] = true;
23         }
24         
25         StringBuilder sb = new StringBuilder();
26         for(char c : stk){
27             sb.append(c);
28         }
29         
30         return sb.toString();
31     }
32 }

類似Remove Duplicate Letters.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM