LeetCode Remove Duplicate Letters

时间:2022-09-30 17:17:50

原题链接在这里:https://leetcode.com/problems/remove-duplicate-letters/

题目:

Given a string which contains only lowercase letters, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

Example 1:

Input: "bcabc"
Output: "abc"

Example 2:

Input: "cbacdcbc"
Output: "acdb"

题解:

Mark the last appearance of each char in s.

For current char, if it is not added in stack.

Keep checking the last added char, if it is bigger than current char and its last appearence is after current index i. Then it could be added later.

Pop it out and mark it unused.

Eventually the chars in stack are expected result.

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

Space: O(1).

AC Java:

 class Solution {
public String removeDuplicateLetters(String s) {
int [] last = new int[26];
for(int i = 0; i<s.length(); i++){
last[s.charAt(i)-'a'] = i;
} Stack<Character> stk = new Stack<>();
boolean [] used = new boolean[26];
for(int i = 0; i<s.length(); i++){
char c = s.charAt(i);
if(used[c-'a']){
continue;
} while(!stk.isEmpty() && stk.peek()>c && last[stk.peek()-'a']>i){
char top = stk.pop();
used[top-'a'] = false;
} stk.push(c);
used[c-'a'] = true;
} StringBuilder sb = new StringBuilder();
for(char c : stk){
sb.append(c);
} return sb.toString();
}
}

类似Smallest Subsequence of Distinct Characters.