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.

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11976305.html